垃圾站 VPS技术 升级PHP7后isset总是返回false问题

升级PHP7后isset总是返回false问题

原先运行环境是 PHP5.6 ,写的函数判断是 isset ($post->user->name),返回结果是若 $post->user->name 不为空则返回 TRUE。 升级到 PHP7 后,发现 isset ($post->user->name) 返回值永远是 FALSE。

分析

Update: this is a revised PR after speaking with Taylor about the intended behavior 
and possible solutions.

PHP 7 has fixed a bug with _isset which affects both the native isset and empty methods. 
This causes specific issues with checking isset or empty on relations in Eloquent. 
In PHP 7 checking if a property exists on an unloaded relation, for example
isset($this->relation->id) is always returning false because unlike PHP 5.6, 
PHP 7 is now checking the offset of each attribute before chaining to the next one. 
In PHP 5.6 it would eager load the relation without checking the offset. 
This change brings back the intended behavior of the core Eloquent model _isset 
method for PHP 7 so it works like it did in PHP 5.6.

For reference, please check the following link, specifically Nikita Popov's 
comment (core PHP dev) - https://bugs.php.net/bug.php?id=69659

机翻如下:

更新:这是在与 Taylor 讨论预期行为和可能的解决方案后修订的 PR。

PHP 7 修复了 _isset 的错误,该错误会影响本机 isset() 和 empty() 方法。
这会导致检查 isset 或 empty 的特定问题。
在 PHP 7 中检查属性是否存在于未加载的关系上,例如 isset($this->relation->id) 
总是返回 false,因为与 PHP 5.6 不同,PHP 7 现在在链接到下一个属性之前
检查每一个属性的偏移量(即先判断 isset($this->relation))。在 PHP 5.6 中,
它会优先加载关系而不检查偏移量
(本例中就会出现 Notice: Undefined index: relation in test.php on line 2)。
此更改恢复了 PHP 7 的核心 Eloquent 模型 _isset 方法的预期行为,
因此它的工作方式与 PHP 5.6 中的一样。

作为参考,请查看以下链接,特别是 Nikita Popov 的评论(核心 PHP 开发人员)
 - https://bugs.php.net/bug.php?id=69659

结论:在 PHP 中非要使用 isset ($post->user->name) 的方式,需要在前面先定义 $post->user->name,比如:

$name= $post->user->name; //先执行一次,$post->user->name,也就是
                          //将 user 放在 post 的 relations 中,
                          //这样 isset ($post->user) 才会为 true,
                          //随后的 isset ($post->user->name) 才为 true
if (isset ($post->user->name)){
...
}

 

上一篇
下一篇
联系我们

联系我们

返回顶部