PHP 中的逻辑与赋值运算符优先级

logical vs assignment operator precedence in PHP

最近我发现了这样的片段:

$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;

产生输出 1:3。 通过查看运算符 precedence sheet,我发现逻辑运算符 ||&& 的优先级高于赋值运算符 =。所以第一个表达式应该被评估为 $x = (2 && $y) = 3; 变成 $x = (2 && null) = 3; 最后评估为 $x = false = 3; 其次 - 赋值运算符具有正确的结合性,因此解释器应该尝试执行 false = 3 这是非法的当然。所以在我看来,上面提到的代码片段根本不应该编译并且必须抛出解析或 运行-time 错误。但是该脚本不会生成 1:3。这意味着解释器执行的操作是:

a) $y=3

b) 2 && $y

c) $x = (2 && $y)

为什么是这样而不是根据运算符优先级?

operator precedence sheet您link单独说明:

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”表达式将以这种方式工作。