简体   繁体   English

php 简写 if

[英]php shorthand if

I'm struggling to understand why the following code is echoing out 'FOO2' when i'm expecting 'FOO1'我很难理解为什么当我期待'FOO1'时下面的代码会回显'FOO2'

$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : $tmp == 'foo2' ? 'FOO2' : 'NO FOO';
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');

basically PHP breaks this down to:基本上 PHP 将其分解为:

$tmp = 'foo1';
echo ($tmp == 'foo1' ? 'FOO1' : $tmp == 'foo2') ? 'FOO2' : 'NO FOO';

the part in parentheses will return FOO1 which evaluates to TRUE so the second conditional statement essentially is TRUE? 'FOO2': 'NO FOO';括号中的部分将返回FOO1其评估结果为TRUE所以第二个条件语句本质上是TRUE? 'FOO2': 'NO FOO'; TRUE? 'FOO2': 'NO FOO'; – which in turn always evaluates to 'FOO2' – 反过来总是评估为'FOO2'

Note: This is different from C ternary operator associativity注意:这与 C 三元运算符关联性不同

$tmp = 'foo1';
if($tmp == 'foo1') echo 'FOO1';
else if($tmp == 'foo2') echo 'FOO2';

As you have just found out, ternary operators are a minefield of confusion, especially when you try to nest stack them.正如您刚刚发现的那样,三元运算符是一个混乱的雷区,尤其是当您尝试 嵌套 堆栈它们时。 Don't do it!不要这样做!

Edit:编辑:
The PHP manual also recommends not stacking ternary operators:- PHP 手册还建议不要堆叠三元运算符:-

It is recommended that you avoid "stacking" ternary expressions.建议您避免“堆叠”三元表达式。 PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:在单个语句中使用多个三元运算符时 PHP 的行为并不明显:

See example 3 on this page of the PHP Manual请参阅PHP 手册此页面上的示例 3

$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM