问题
Found some interesting code snippet today. Simplified, it looks like this:
$var = null;
$var or $var = '123';
$var or $var = '312';
var_dump($var);
The thing is that, as i know, precedence of assignment is higher that OR, so, as i assume, var_dump
should output 312
(first - assign, second - compare logically). But result is defferent, i getting 123
(first - check if $var
converting to true
, second - if not, assign value).
The questions is how does it work?
Why behavior is the same for or
and ||
?
回答1:
You can see examples about this behaviour in Logical Operators
Also you can read artical about Short-circuit evaluation
The short-circuit expression
x Sand y
(using Sand to denote the short-circuit variety) is equivalent to the conditional expressionif x then y else false;
the expressionx Sor y
is equivalent toif x then true else y
.
In php.
return x() and y();
equal to
if (x())
return (bool)y();
else
return false;
return x() or y();
equal to
if (x())
return true;
else
return (bool)y();
So, deal is not just in precedence.
回答2:
It same as
$var = null;
if(!$var)$var = '123';
if(!$var)$var = '321';
var_dump($var);
来源:https://stackoverflow.com/questions/15835817/operators-precedence-of-or-and-assignment