2013-07-01 118 views
0

我爲Joomla 2.5創建了一個新組件。我有兩個功能:如何在其他函數中調用函數變量

public function getBase(){ 

    if(JFactory::getUser()->guest) { 
     $this->base = 'Гость'; 
    } 
    else { 
     $user =& JFactory::getUser(); 
     $usr_id = $user->get('id'); 
     /**/ 

     $this->base = 'Гуд юзер id '.$usr_id.''; 
     /*Get database info*/  
    } 

    return $this->base; 
} 

public function getGetInfo() { 

    $this->getinfo = '11 '.$usr_id.''; 

    return $this->getinfo; 
} 

請告訴我如何使用$usr_id = $user->get('id');getBase()getGetInfo()功能。謝謝您的幫助。

回答

0

如果這兩個函數在同一個類中,那麼可以使用類變量

class MyClass 
{ 
    private $user; 

    public function getBase() 
    { 
     // --- 
     $user =& JFactory::getUser(); 

     // Set user class variable 
     $this->user = $user; 
     // --- 
    } 

    public function getGetInfo() 
    { 
     // Now you can use the user 
     $user = $this->user; 

     // --- 
    } 
} 

。如上還解釋,你可以(儘管你不希望,因爲它是重複代碼),只需調用在getGetInfo()方法相同的代碼來獲取用戶。不要重複你的代碼,使用類變量。

+0

THX!工作正常! –

0

您有兩個選擇來達到這個要求。

一個是像上面那樣從用戶對象訪問它。

$user =& JFactory::getUser(); 
$user_id = $user->id; 

或者你必須創建該類的類變量一樣

public $current_user; 

and inside the public function getBase(){ 

$this->current_user = $user->get('id'); 
} 

那麼這個$this->current_user變量將可以在全班功能

相關問題