三元算子左联想 [英] Ternary operator left associativity
问题描述
在PHP手册中,我在操作员"下找到了以下用户提供的说明" .
In the PHP manual, I find the following 'user contributed note' under "Operators".
请注意,在php中,三元运算符?:具有左联想性,与C和C ++中具有右联想性的情况不同.
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.
您不能编写这样的代码(如您在C/C ++中所习惯的那样):
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
.
I actually try it and it really prints four
. However I could not understand the reason behind it and still feel it should print two
or other
.
有人可以解释一下这里发生了什么以及为什么要打印四个"吗?
Can someone please explain what is happening here and why it is printing 'four'?
推荐答案
在任何理智的语言中,三元运算符都是右关联的,因此您可以期望这样的代码被解释为:
In any sane language, the ternary operator is right-associative, such that you would expect your code to be interpreted like this:
$a = 2;
echo ($a == 1 ? 'one' :
($a == 2 ? 'two' :
($a == 3 ? 'three' :
($a == 4 ? 'four' : 'other')))); # prints 'two'
但是,PHP三元运算符是奇怪的左关联,因此您的代码实际上等效于此:
However, the PHP ternary operator is weirdly left-associative, such that your code is actually equivalent to this:
<?php
$a = 2;
echo (((($a == 1 ? 'one' :
$a == 2) ? 'two' :
$a == 3) ? 'three' :
$a == 4) ? 'four' : 'other'); # prints 'four'
如果仍然不清楚,则评估如下:
In case it still isn't clear, the evaluation goes like this:
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';
这篇关于三元算子左联想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!