【发布时间】:2011-09-07 15:14:51
【问题描述】:
我不明白那个输出 ("four") 是怎么来的?
$a = 2;
echo
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 5 ? 'four' :
'other'
;
// prints 'four'
我不明白为什么会打印“four”。
【问题讨论】:
-
@riky: 是的,但是
$a=2在他的代码中...... -
YA 所以根据您的登录,它将打印“两个”。你能解释一下你到底想要什么吗?
-
== 运算符的优先级高于 ternar 运算符。所以必须使用方括号进行分组。 php.net/manual/en/language.operators.precedence.php
-
除了完全不可读之外,您还应该避免堆叠三元运算符。请参阅手册中的注释de2.php.net/manual/en/language.operators.comparison.php
-
在 C/C++/Java 中你会得到“两个”。 PHP 不同的实际原因是因为 PHP 从左到右而不是从右到左处理
?:关联性。这是众所周知的 PHP 错误设计。请参阅 this explanation 和 that criticism。这个问题不是题外话,因为这是一个真实且有问题的 PHP 优先级问题。
标签: php ternary-operator operator-precedence