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

小助手读文章 00:00 / 00:00

温馨提示:
本文所述内容不具普遍性,可能因操作环境差异而与实际有所出入,故请勿照搬照抄,仅供参考。

问题

原先运行环境是 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)){
...
}

番外:关于 ->

类是一个物体,比如一个箱子,或者一个自行车,可以写一个类:

class box{}

这个就是箱子类,箱子有大小和体积,还可以被打开和装入东西,大小和体积就是属性,打开和装入东西就是方法

class box{
   var 高;
   var 宽;

   function 打开(){

   }
}

$box = new box();   //初始化类到一个变量box里面
echo $box->高;      //我知道了它的高
$box->打开();       //我打开它了

参考文章:

1、《升级 PHP7 后 isset 不太对了
2、《Account for __isset changes in PHP 7


ArmxMod for Typecho
个性化、自适应、功能强大的响应式主题

推广

 继续浏览关于 php教程问题isset 的文章

 本文最后更新于 2022/02/15 19:38:10,可能因经年累月而与现状有所差异

 引用转载请注明: VirCloud's Blog > 建站 > 升级 PHP7 后 isset 总是返回 false 问题

精选评论

  1. ArmxMod
    ArmxMod 回复

    Windows 10Chrome 97.0.4692.71来自 福建 的大神

    所以导致在 5.x 正常,到 7.x 就不工作问题