Search code examples
phpoperator-keywordternary

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


Solution

  • That's because operators precedence. Do

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

    -so assignment will be evaluated with higher precedence.