wake-up-neo
wake-up-neo

Reputation: 814

PHP bug with ternary operator?

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

Upvotes: 0

Views: 638

Answers (4)

IMSoP
IMSoP

Reputation: 97688

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;

Upvotes: 0

wake-up-neo
wake-up-neo

Reputation: 814

more elegant solution:

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

Upvotes: 2

Sujan Shrestha
Sujan Shrestha

Reputation: 419

Can't we do just:

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

function bar() {
    return "some_value";
}

foo();

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

That's because operators precedence. Do

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

-so assignment will be evaluated with higher precedence.

Upvotes: 11

Related Questions