到目前爲止,當我想知道用戶是否登錄時,我使用了Yii::app()->user->isGuest
。Yii:使用getIsGuest()或isGuest
但是,有一種方法稱爲getIsGuest()
,它返回isGuest
變量。
if (!Yii::app()->user->getIsGuest())
我的問題是,我應該使用getIsGuest()
呢?使用getIsGuest()
是正確的方法?或者這並不重要,他們都糾正方式?
到目前爲止,當我想知道用戶是否登錄時,我使用了Yii::app()->user->isGuest
。Yii:使用getIsGuest()或isGuest
但是,有一種方法稱爲getIsGuest()
,它返回isGuest
變量。
if (!Yii::app()->user->getIsGuest())
我的問題是,我應該使用getIsGuest()
呢?使用getIsGuest()
是正確的方法?或者這並不重要,他們都糾正方式?
實際上,$class->getAttribute()
和$class->attribute
之間沒有區別。但是,知道後面發生的事情是很好的。
Yii廣泛使用php的神奇方法。在這種情況下,它使用__set和__get魔術方法來實現getter和setter。由於php的官方文檔定義爲__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;
}
}
如果你想獲得attribute
屬性值必須調用getAttribute()
方法,你不能得到attribute
像下面(因爲你必須attribute
財產無法訪問):
$test=new Test();
echo $test->attribute;
但隨着__get魔術方法也可以實現爲:
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;
}
}
現在,你能得到像下面attribute
值:
$test=new Test();
echo $test->attribute;
要了解更多關於PHP的魔術方法看一下在PHP的官方文檔:
這並不重要。如果您撥打user->isGuest
,則內部調用方法user->getIsGuest()
。這只是一種別名。
我讀源文件並找不到任何名爲isGuest的變量或方法,那麼這是如何工作的? – user3803707 2014-09-11 13:59:08
當你調用'isGuest'時,PHP用'CWebUser'類搜索一個名爲'$ isGuest'的公共屬性,找不到它,然後查找定義爲get()'....在這種情況下'getIsGuest()'並使用它的返回值 –
2014-09-11 14:37:08