php – 为什么isset()总是在自定义Object上返回FALSE
发布时间:2020-12-13 22:10:18 所属栏目:PHP教程 来源:网络整理
导读:我无法理解这种行为:我的isset()检查总是在具有值肯定的属性上返回false! ?php class User { protected $userId; // always filled protected $userName; // always filled /** * Magic method for the getters. * * @param type $property * @return sel
我无法理解这种行为:我的isset()检查总是在具有值肯定的属性上返回false!
<?php class User { protected $userId; // always filled protected $userName; // always filled /** * Magic method for the getters. * * @param type $property * @return self|property */ public function __get($property) { if (property_exists($this,$property)) { return $this->$property; } else { throw new Exception('property '.$property.' does not exist in '.__CLASS__.' class'); } } } ?> 当我从另一个类检查此变量时,使用以下内容: isset($loggedUser->userName); // loggedUser is my instantiation of the User.php 它返回FALSE ??但是当我在User.php中重载__isset()函数时,我得到了正如我预期的那样: public function __isset($name) { return isset($this->$name); } 只是要清楚: echo $loggedUser->name; // result "Adis" isset($loggedUser->name); // results in FALSE,but why? 谢谢你的帮助! 解决方法
$userName受保护,这意味着您无法在类外部访问它,在此示例中是来自$loggedUser init.
您需要以下之一: 1)公开 2)编写自定义方法 3)制作魔术(__ isset)功能 编辑:当对无法访问的对象属性使用isset()时,将调用__isset()重载方法,如果声明为isset() php docs 我希望这能解释它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |