PHP中的逻辑与赋值运算符优先级 [英] logical vs assignment operator precedence in PHP
问题描述
最近我发现了这样的片段:
Recently i came upon such snippet:
$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;
产生输出 1:3
.通过查看运算符 precedence sheet 我看到逻辑运算符 ||
和 &&
比赋值运算符 =
具有更高的优先级.所以第一个表达式应该被评估为 $x = (2 && $y) = 3;
变成 $x = (2 && null) = 3;
code> 并最终计算为 $x = false = 3;
其次 - 赋值运算符具有右结合性,因此解释器应该尝试执行 false = 3
这当然是非法的.所以在我看来,上面提到的代码片段根本不应该编译,并且必须抛出解析或运行时错误.但不是那个脚本产生 1:3.这意味着解释器执行的操作是:
Which produces output 1:3
.
By looking at operator precedence sheet i see that logical operators ||
and &&
has higher precedence than assignment operator =
. So first expression should be evaluated as $x = (2 && $y) = 3;
which becomes $x = (2 && null) = 3;
and finally evaluates to $x = false = 3;
Secondly - assignment operator has right associativity, so interpreter should try to execute false = 3
which is illegal of course. So in my opinion above mentioned code snippet should not compile at all and must throw parse or run-time error. But instead of that script produces 1:3. Which means that interpreter executed actions are:
a) $y=3
b) 2 &&$y
b) 2 && $y
c) $x = (2 && $y)
c) $x = (2 && $y)
为什么是这样而不是根据运算符优先级?
Why it is so and not according to operator precedence ?
推荐答案
运算符优先级表,您作为单独的注释链接到状态:
The operator precedence sheet you link to states as a separate note:
尽管 = 的优先级低于大多数其他运算符,但 PHP 将仍然允许类似于以下的表达式:if (!$a = foo()), in这种情况下 foo() 的返回值放入 $a 中.
Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
因此,实际上,表达式中的赋值将被视为有点像子表达式.文档中并不清楚具体如何以及何时发生这种情况,文档中只是指出similar"表达式会以这种方式工作.
So, in effect, an assignment inside an expression will be treated somewhat like a sub-expression. Exactly how and when this will happen isn't clear from the documentation, which just states that "similar" expressions will work this way.
这篇关于PHP中的逻辑与赋值运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!