1

Yes, I know this is very bad code, but I'd still like to understand it:

$out = $a > 9 && $a < 15 ? "option1" : $a < 5 ? "option2" : "option3";

$out = $a > 9 && $a < 15 ? "option1" : ($a < 5 ? "option2" : "option3");

If $a is 11, then the result of the 1st line is "option 2", but in the 2nd line, the result is "option 1" - what effect is the pair of brackets having?

4

2 回答 2

7

您得到的未加括号的代码被解析为:

$out = (
    (
        ($a < 9 && $a < 15)
        ? ("option1")
        : ($a < 5) 
    )
    ? ( "option2" )
    : ( "option3" )
);

这是因为PHP 的三元运算符是左关联的。这与它在所有其他语言中的工作方式完全相反,最终以一种令人惊讶的(而且几乎总是无用的!)方式解释链式三元表达式。这被广泛认为是一个错误,但“太旧而无法修复”,就像 C 的二进制运算符的一些类似优先级问题一样。

在第二个表达式中添加括号会产生预期的结果:

$out = (
    ($a > 9 && $a < 15)
    ? ("option1")
    : (
        ($a < 5)
        ? ("option2")
        : ("option3")
    )
);
于 2013-09-16T23:30:15.290 回答
4

第一行解析如下:

$out = ($a > 9 && $a < 15 ? "option1" : $a < 5) ? "option2" : "option3";

这相当于以下(当$a == 11):

$out = "option1" ? "option2" : "option3";

"option1"强制为 boolean is true,因此上述计算结果为"option2"

第二个正在按照您的预期进行解析:

$out = ($a > 9 && $a < 15) ? "option1" : ($a < 5 ? "option2" : "option3");
于 2013-09-16T23:22:01.947 回答