javascript - 关于 JavaScript 和 PHP 赋值运算符 : Why the different results?

标签 javascript php

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 赋值运算符不同的原因是什么?

是否与运算符优先级相关?

我想知道原因是什么。谢谢!

最佳答案

不,运算符优先级不会影响评估顺序,因此在复杂评估中使用赋值并重用评估结果始终是未定义的。

From the PHP manual :

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/

相关文章:

javascript - Jquery Datatables 扩展细节的持久性

javascript - 如何将 highcharts 包含在 bower 中?

javascript - 列表更改 onclick

php - Laravel 关系计数()

javascript - 脚本 "src"标签问题

javascript - jQuery Colorbox 插件不加载图像

php - 使用mysqli发布到数据库

php - 显示与关系的帖子评论 - Laravel

php - 在产品搜索查询中添加 Hook

php - 如何跟踪网站上的用户使用情况?