Question

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

Was it helpful?

Solution

That's because operators precedence. Do

function foo() {
    return ($result = bar()) ? $result : false;
}

-so assignment will be evaluated with higher precedence.

OTHER TIPS

more elegant solution:

function foo() {
    return bar() ?: false; 
}

Can't we do just:

function foo() {
    return bar() ? $result : false;
}

function bar() {
    return "some_value";
}

foo();

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top