Php Yii:使用getIsGuest()或isGuest

Php Yii:使用getIsGuest()或isGuest,php,authentication,methods,yii,Php,Authentication,Methods,Yii,到目前为止,当我想知道用户是否登录时,我使用了Yii::app()->user->isGuest 但是,有一个名为getIsGuest()的方法,它返回isGuest变量 if (!Yii::app()->user->getIsGuest()) 我的问题是,我应该改用getIsGuest()?使用getIsGuest()是正确的方法吗?或者这不重要,而且他们都是正确的方法?这真的不重要。如果您调用user->isGuest方法user->getIsGuest()将在内部调用。它只是

到目前为止,当我想知道用户是否登录时,我使用了
Yii::app()->user->isGuest

但是,有一个名为
getIsGuest()
的方法,它返回
isGuest
变量

if (!Yii::app()->user->getIsGuest())

我的问题是,我应该改用
getIsGuest()
?使用
getIsGuest()
是正确的方法吗?或者这不重要,而且他们都是正确的方法?

这真的不重要。如果您调用
user->isGuest
方法
user->getIsGuest()
将在内部调用。它只是一种别名。

实际上,
$class->getAttribute()
$class->attribute
之间没有区别。但这是很好的了解背后发生了什么

Yii广泛使用php魔术方法。在本例中,它使用_set和_get魔术方法来实现getter和setter。php的官方文档定义了
\uu get()

__get()用于从不可访问的属性读取数据

举个例子:

class Test{
    private $attribute;
    private $attribute2;
    private $attribute3;
    public function getAttribute(){
        return $this->attribute;
    }
    public function getAttribute2(){
        return $this->attribute2;
    }
    public function getAttribute3(){
        return $this->attribute3;
    }
}
如果要获取
属性
属性值,必须调用
getAttribute()
方法,并且不能像下面那样获取
属性
(因为您无法访问
属性
属性):

但使用u_getmagic方法,它可以实现为:

class Test{
    private $attribute;
    private $attribute2;
    private $attribute3;
    //__GET MAGIC METHOD
    public function __get($name)
    {
        $getter='get'.$name;
        if(method_exists($this,$getter))
        return $this->$getter();
    }

    public function getAttribute(){
        return $this->attribute;
    }
    public function getAttribute2(){
        return $this->attribute2;
    }
    public function getAttribute3(){
        return $this->attribute3;
    }
}
现在,您可以获得如下所示的
属性
值:

$test=new Test();
echo $test->attribute;
要了解有关php神奇方法的更多信息,请查看php的官方文档:


我阅读了源文件,但找不到任何名为isGuest的变量或方法,那么这是如何工作的呢?当调用
isGuest
时,PHP使用
CWebUser
类搜索名为
$isGuest
的公共属性,但找不到它,然后它会查找定义为
get()的
getter
函数/方法
…在本例中,
getIsGuest()
并使用其返回值
$test=new Test();
echo $test->attribute;