问题
function foo() {
return $result = bar() ? $result : false;
}
function bar() {
return "some_value";
}
foo();
Notice: Undefined variable: result
Is this a bug?
bar() should be saved to $result, but it doesn't. However the condition works fine and it's trying to return $result or false statement (in case bar() is NULL or false)
PHP 5.4.24
回答1:
That's because operators precedence. Do
function foo() {
return ($result = bar()) ? $result : false;
}
-so assignment will be evaluated with higher precedence.
回答2:
more elegant solution:
function foo() {
return bar() ?: false;
}
回答3:
Can't we do just:
function foo() {
return bar() ? $result : false;
}
function bar() {
return "some_value";
}
foo();
回答4:
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;
来源:https://stackoverflow.com/questions/22633643/php-bug-with-ternary-operator