JavaScript 代码:
var a = 1, b = 2;
a = b + (b = a) * 0;
// result a = 2, b = 1;
PHP 代码 1:
$a = 1;
$b = 2;
$a = $b + ($b = $a) * 0;
// result $a = 1, $b = 1;
PHP 代码 2:
$a = 1;
$b = 2;
$a = (int)$b + ($b = $a) * 0;
// result $a = 2, $b = 1;
导致 PHP 和 JavaScript 赋值运算符不同的原因是什么?
是否与运算符优先级相关?
我想知道原因是什么。谢谢!
最佳答案
不,运算符优先级不会影响评估顺序,因此在复杂评估中使用赋值并重用评估结果始终是未定义的。
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
简而言之,$b + ($b = $a)
的输出是未定义的,因为分组会覆盖优先级,并且无论如何都不会强制赋值是否发生在获取左操作数之前添加或之后。 优先级定义明确,执行/评估顺序不是。
关于javascript - 关于 JavaScript 和 PHP 赋值运算符 : Why the different results?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24426293/