operator 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 error trying property of non-object
regarding line $set = \app\set::find($notes->newset)
passing through elseif
block should mean $notes
assigned in elseif
, value of $notes->newset
found.
i don't know why above snippet not works! works if uncomment // $notes = json_decode($op->notes);
the php version 7.0.18
as pointed out @zerkms, because of operator precedence, part of expression following
$notes =
is evaluated first, , in success case,
json_decode($op->notes) && isset($notes->newset)
evaluates true
, resulting in $notes
being assigned true
, rather json_decode()
d data want.
to fix issue, wrap assignment in parenthesis, , evaluated first, and, pointed out @jh1711, make sure verify decoded data object ( instance of stdclass
), rather array:
} elseif (($notes = json_decode($op->notes)) instanceof \stdclass && isset($notes->newset)) { $set = \app\set::find($notes->newset); $settitle = $set->title; }
for reference, see:
Comments
Post a Comment