2011-08-22 82 views
5

我很高興看到一個變量範圍問題。也許我只是需要更多的咖啡...PHP/CodeIgniter - 在__construct()中設置變量,但不能從其他函數訪問

這是我(簡化)代碼 - 這是笨2:

class Agent extends CI_Controller {  

public function __construct() 
{ 
    parent::__construct(); 

    $this->load->model('agent_model'); 

    // Get preliminary data that will be often-used in Agent functions 
    $user = $this->my_auth_library->get_user(); 
    $agent = $this->agent_model->get_agent($user->id); 
} 

public function index() 
{  
    $this->template->set('info', $this->agent_model->get_info($agent->id)); 

    $this->template->build('agent/welcome'); 
} 

不幸的是,當我運行索引功能,有人告訴我:

A PHP Error was encountered 

Severity: Notice 
Message: Undefined variable: agent 
Filename: controllers/agent.php 
Line Number: 51 

第51行是索引函數的第一行。出了什麼問題?這是範圍問題還是其他問題?

謝謝!

+0

你沒有設置任何類變量,只是函數變量得到它們。見http://www.php.net/manual/en/language.oop5.properties.php – hakre

回答

11

您沒有設置索引中的作用$agent,如果你想在構造函數訪問,那麼你必須將它們設置爲一個類屬性,即設置變量:$this->Agent = ...;,並與$this->Agent->id訪問它們以同樣的方式。 (我會利用他們去證實它們是對象,而不僅僅是變量)例如:

$this->User = $this->my_auth_library->get_user(); 
$this->Agent = $this->agent_model->get_agent($user->id); 

的構造方法的行爲同任何其他類的方法,它唯一的特殊性質是,當類是它的自動運行實例化,正常變量作用域仍然適用。

+0

感謝解釋這一點的評論 - 我曾假設__construct()在函數之前有一個'prepended',它仍然是無障礙。謝謝! – Jack

9

你需要定義變量構造函數外,像這樣:

class Agent extends CI_Controller { 

    private $agent; 
    private $user; 

    public function __construct() { 

     parent::__construct(); 

     $this->load->model('agent_model'); 

     // Get preliminary data that will be often-used in Agent functions 
     $this->user = $this->my_auth_library->get_user(); 
     $this->agent = $this->agent_model->get_agent($user->id); 
    } 

    public function index() { 

     $this->template->set('info', $this->agent_model->get_info($this->agent->id)); 

     $this->template->build('agent/welcome'); 
    } 
} 

,那麼你可以設置和使用$this->agent

+0

謝謝'$ this-> user - > ...'很好。謝謝! – Jack

+1

+1在分配之前聲明它們是全班級的,因此可以更容易地跟蹤整個班級的情況。 – jondavidjohn

相關問題