Using the side-effect of a sub-expression within the same expression is always risky, even if the operator precedence is correct.
Even if it's necessary to evaluate the result of $result = bar()
in order to test the condition, there's no general guarantee that that result will be used later in the expression, rather than a value taken before the assignment.
See for instance Operator Precedence vs Order of Evaluation which discusses this in the context of C++, and gives this classic example:
a = a++ + ++a;
Having side-effects inside a condition is also hard to read - it might be read as $result == bar()
, which would mean something entirely different.
So, in this case, the problem was just PHP's unfortunate associativity of ? :
, but writing code like this is a bad idea anyway, and you can trivially make it much more readable and reliable by taking the side-effect out of the left-hand side:
$result = bar();
return $result ? $result : false;
Or in this case, assuming $result
is not global
or static
:
return bar() ?: false;
bar()
so returntrue
=> thus assigning$result
which is undefined. What's wrong with that ? – Stomatitis