About JavaScript and PHP Operators: Why Different Results?

JavaScript Code:

var a = 1, b = 2; a = b + (b = a) * 0; // result a = 2, b = 1; 

PHP code 1:

 $a = 1; $b = 2; $a = $b + ($b = $a) * 0; // result $a = 1, $b = 1; 

PHP 2 code:

 $a = 1; $b = 2; $a = (int)$b + ($b = $a) * 0; // result $a = 2, $b = 1; 

What causes the difference between PHP and JavaScript assignment operations?

Is this related to operator priority?

I want to know what is the reason. Thanks!

+6
source share
2 answers

No, the priority of the operator does not affect the evaluation order, so the use of assignments in complex estimates, the reuse of the evaluation result is always undefined.

From the PHP manual :

The priority and associativity of operators determine only how expressions are grouped, they do not determine the order of evaluation. PHP should not (in general) indicate in what order the evaluated expression and code that involves a certain evaluation order should be avoided , as the behavior may vary between versions of PHP or depending on the surrounding code.

In short, the output of $b + ($b = $a) is undefined, since the grouping redefines the priority and does not in any way take effect if there is a assignment before extracting the left addition operand or after. The priority is well defined, the execution / evaluation order is not.

+4
source

To increase @NielsKeurentjes answer with a JavaScript perspective:

(Unlike PHP) JavaScript sets the order of operations (operands are evaluated from left to right), which makes it work as expected.

From the ECMAScript specification :

The product of AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:

  • Let lref be the result of evaluating AdditiveExpression .
  • Let lval be GetValue (lref).
  • Let rref be the result of evaluating MultiplicativeExpression .
  • Let rval be GetValue(rref) .
  • ...
+1
source

Source: https://habr.com/ru/post/971370/


All Articles