在IF中定义变量在PHP中不起作用

时间:2017-07-27 21:59:12

标签: php operator-precedence

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

上述elseif语句生成有关行Trying to get property of non-object的错误$set = \App\Set::find($notes->newSet)

传递此elseif广告块意味着在$notes中分配elseif并找到$notes->newSet的值。

我不知道为什么上面的代码段不起作用!它仅在我取消注释// $notes = json_decode($op->notes);

时才有效

PHP版本为7.0.18

1 个答案:

答案 0 :(得分:4)

正如@zerkms所指出的那样,由于运算符优先级,表达式的部分在

之后
$notes = 
首先评估

,在成功案例中,

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

评估为true,导致$notes被分配true,而不是您想要的json_decode() d数据。

要解决此问题,请在括号中包装赋值,并首先对其进行求值,并且如@jh1711所指出的,确保验证解码数据实际上是一个对象({{1}的实例}),而不是数组:

stdClass

供参考,见: