Search code examples
phpoperatorsassignment-operator

Operators precedence of "or" and assignment


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 ||?


Solution

  • 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.