在 PHP 手册中,我找到了 the following 'user contributed note'在“运营商”下。
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.
You cannot write code like this (as you may have accustomed to in C/C++):
<?php
$a = 2;
echo (
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
我实际尝试了一下,它确实打印了 four
。但是我无法理解它背后的原因,仍然觉得它应该打印 two
或 other
。
有人可以解释这里发生了什么以及为什么它打印“四”吗?
在任何理智的语言中,三元运算符都是右结合的,因此您期望您的代码被解释成这样:
$a = 2;
echo ($a == 1 ? 'one' :
($a == 2 ? 'two' :
($a == 3 ? 'three' :
($a == 4 ? 'four' : 'other')))); # prints 'two'
但是,PHP 三元运算符是奇怪的左结合运算符,因此您的代码实际上等同于:
<?php
$a = 2;
echo (((($a == 1 ? 'one' :
$a == 2) ? 'two' :
$a == 3) ? 'three' :
$a == 4) ? 'four' : 'other'); # prints 'four'
如果还是不清楚,可以这样评价:
echo ((((FALSE ? 'one' :
TRUE) ? 'two' :
$a == 3) ? 'three' :
$a == 4) ? 'four' : 'other');
echo ((( TRUE ? 'two' :
$a == 3) ? 'three' :
$a == 4) ? 'four' : 'other');
echo (( 'two' ? 'three' :
$a == 4) ? 'four' : 'other');
echo ( 'three' ? 'four' : 'other');
echo 'four';