为什么isset()总是在自定义Object上返回FALSE

adi*_*dis 3 php

我无法理解这种行为:我的isset()检查总是在具有值的值上返回falseproperty!

<?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');
        }
    }

  }

?>
Run Code Online (Sandbox Code Playgroud)

当我从另一个类检查此变量时,使用以下内容:

isset($loggedUser->userName); // loggedUser is my instantiation of the User.php
Run Code Online (Sandbox Code Playgroud)

它返回FALSE?? 但是当我__isset()在User.php中重载函数时,我TRUE按照预期返回:

public function __isset($name)
{
    return isset($this->$name);
}
Run Code Online (Sandbox Code Playgroud)

只是要清楚:

echo $loggedUser->name;   // result "Adis"
isset($loggedUser->name); // results in FALSE, but why?
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Mar*_*c B 6

protected属性仅在对象的方法中可见.从外部访问隐藏它们.


class prot_text {
    protected $cannot_see_me;
    function see_me() {
       echo $this->cannot_see_me;
    }
}

$x = new prot_text();
echo $x->cannot_see_me; // does not work - accessing from "outside"
$x->see_me(); // works, accessing the attribute from "inside".
Run Code Online (Sandbox Code Playgroud)


Fla*_*ame 5

$userName受保护,这意味着您无法在类外部访问它,在此示例中是从$loggedUserinit.您需要以下之一:
1)使它public
2)编写自定义方法
3)制作魔术(__ isset)函数

编辑:在无法访问的对象属性上使用isset()时,如果声明,将调用__isset()重载方法.isset()php docs

我希望这能解释它.