2014-02-13 31 views
0

我對這個OOP概念有點困惑。我正在嘗試爲下面的可用性設置一個值。使用案例方法的PHP OOP

即:

protected $isAdmin; 

我想用一個setter和getter設置這個值;並使用caseMethod來設置setter的值。

下面可能會更容易展示您;

protected $isAdmin = null; 

    public function isAdminWorker() 
    { 
     //this will get the preset values for the user; i.e admin worker or visitor. 
     $theRole = $this->zfcUserAuthentication()->getAuthService()->getIdentity()->getRole(); 

    switch($theRole) 
    {    
      case 'admin': 

       $this->setIsAdmin($theRole); 

     break; 

      case 'visitor': 
       $this->setVisitor($theRole); 
     break; 
     }  
    } 

public function setIsAdmin($isAdmin) 
    { 
     $this->isAdmin = $isAdmin; 
    } 

    public function getIsAdmin() 
    { 

     return $this->isAdmin; 
    } 

當我叫$this->getIsAdmin()它總是返回NULL值。所以,Case方法基本上沒有設置正確的值。

我很迷惑關於使用getter和setter方法設置值,並會在我出錯的地方給出一些建議。

+0

OK,所以這種方法很可能無法設置正確的值。看看'$ this-> isAdmin'在前後的價值。檢查'$ theRole'的值。這是基本的調試,我不知道你期望在這裏有什麼樣的幫助。 – Jon

+0

就像已經說過的那樣,檢查'$ theRole'的值。可能你的方法'$ this-> zfcUserAuthentication() - > getAuthService() - > getIdentity() - > getRole()'不返回「admin」或「visitor」。 – kinkee

+0

hi jon and kinkee。我已經完成了所有基本的調試。設置之前的值爲空,設置後的值爲空。我對這一個確實有些不解。 bascially。它看起來像我的二傳手和getter方法不正確 – andreea115

回答

0

我obviouly困惑使用getter和setter方法設定值,並會在並欣賞我在那裏出了錯一些建議

isFoo()hasFoo()(「是」或「有」的方法)通常用於表示boolean結果。

我認爲如果您將isget方法結合在一起,會導致混淆。

嘗試封裝方法,以便他們執行一項任務;可能的解決方案可能是。

class MyClass { 

    protected $identity; 

    protected $role; 

    public function getIdentity() 
    { 
    if (null == $this->identity) { 
     $this->identity = $this->zfcUserAuthentication()->getAuthService()->getIdentity(); 
    } 
    return $this->identity; 
    } 

    public function getRole() 
    { 
    if (null == $this->role) { 
     $this->role = $this->getIdentity()->getRole(); 
    } 
    return $this->role; 
    } 

    public function isAdmin() 
    { 
    return ('admin' === $this->getRole()); 
    } 

    public function isVisitor() 
    { 
    return ('visitor' === $this->getRole()); 
    } 

} 

這給你一個更清晰的API,無需「設置」任何角色等

+0

你好AlexP感謝你的建議;我現在就試試。溫暖的問候安德列亞 – andreea115