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 code 2:
$a = 1;
$b = 2;
$a = (int)$b + ($b = $a) * 0;
// result $a = 2, $b = 1;
What causes the difference between PHP and JavaScript assignment operators?
Is it operator precedence related?
I want to know what the reasons are. Thanks!
The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
Assignment operators. An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .
Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.
= will concatenate strings. The + operator is the addition operator. += will add numeric values.
No, operator precedence doesn't factor into evaluation order, therefore using assignments in complex evaluations reusing the result of the evaluation is always undefined.
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.
In short, the output of $b + ($b = $a)
is undefined, since the grouping overrides precedence, and does not in anyway enforce whether the assignment occurs before fetching the left operand of the addition or after. The precedence is well defined, the execution/evaluation order is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With