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

时间:2012-10-15 16:04:45

标签: php

我无法理解这种行为:我的isset()检查总是在property上返回 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()函数时,我得到了TRUE,如我所料:

public function __isset($name)
{
    return isset($this->$name);
}

要明确:

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

感谢您的帮助!

4 个答案:

答案 0 :(得分: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".

答案 1 :(得分:5)

$userName受到保护,这意味着您无法在此类示例中从$loggedUser init访问该类。 您需要以下其中一项:
1)使它成为public
2)编写自定义方法
3)制作魔法(__ isset)功能

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

我希望这可以解释它。

答案 2 :(得分:1)

$ userName受到保护,因此只能从其定义的类内部或任何扩展它的类中访问。

答案 3 :(得分:1)

这是因为该财产受到保护。无法在对象(或子对象)外部访问受保护的属性。重载函数在类中定义,因此工作正常。

这是OOP的一个特点:(http://php.net/manual/en/language.oop5.visibility.php) 如果要使其在任何地方都可访问,请将该属性定义为public,否则将该特定函数包装在公共函数中。