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;