Operators precedence of “or” and assignment

大憨熊 提交于 2019-12-22 13:07:28

问题


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 expression if x then y else false; the expression x Sor y is equivalent to if 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!