Search code examples
phpoperator-precedence

Define variable in "IF" does not work in PHP


...
elseif ($notes = json_decode($op->notes) && isset($notes->newSet)){
           // $notes = json_decode($op->notes);
            $set = \App\Set::find($notes->newSet);
            $setTitle = $set->title;
        }
...

The above elseif statement generates an error Trying to get property of non-object regarding the line $set = \App\Set::find($notes->newSet)

Passing through this elseif block should mean that $notes is assigned in elseif and the value of $notes->newSet is found.

I don't know why the above snippet does not works! It only works if I uncomment // $notes = json_decode($op->notes);

The PHP version is 7.0.18


Solution

  • As pointed out by @zerkms, because of operator precedence, the part of the expression following

    $notes = 
    

    is evaluated first, and in the success case,

    json_decode($op->notes) && isset($notes->newSet)
    

    evaluates to true, resulting in $notes being assigned true, rather than the json_decode()d data you want.

    To fix this issue, wrap the assignment in parenthesis, and it will be evaluated first, and, as pointed out by @jh1711, make sure to verify that the decoded data is actually an object ( an instance of stdClass), rather than an array:

    } elseif (($notes = json_decode($op->notes)) instanceof \stdClass && isset($notes->newSet)) {
        $set = \App\Set::find($notes->newSet);
        $setTitle = $set->title;
    }
    

    For reference, see: