PHP/CodeIgniter-在_construct()中设置变量,但它们';您无法从其他功能访问

PHP/CodeIgniter-在_construct()中设置变量,但它们';您无法从其他功能访问,php,codeigniter,variables,scope,Php,Codeigniter,Variables,Scope,我很高兴有点变量范围问题。也许我需要更多的咖啡 这是我的(简化)代码-这在CodeIgniter 2中: class Agent extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('agent_model'); // Get preliminary data that will be often-us

我很高兴有点变量范围问题。也许我需要更多的咖啡

这是我的(简化)代码-这在CodeIgniter 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');
}
不幸的是,当我运行index函数时,我被告知:

A PHP Error was encountered

Severity: Notice
Message: Undefined variable: agent
Filename: controllers/agent.php
Line Number: 51
第51行是索引函数的第一行。怎么了?这是范围问题还是其他问题


谢谢

您还没有在索引操作中设置
$agent
,如果您想访问构造函数中设置的变量,那么必须将它们设置为类属性,即:
$this->agent=
,并使用
$this->Agent->id
以相同的方式访问它们。(我会将它们大写,以表明它们是对象,而不仅仅是变量)例如:

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

构造函数的行为与任何其他类方法相同,它唯一的特殊属性是在实例化类时自动运行,普通变量范围仍然适用。

您需要在构造函数之外定义变量,如下所示:

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

设置和获取它们。您没有设置任何类变量,只设置函数变量。请参阅,感谢您对这一点的解释-我曾假设_construct()在函数之前“预先”了它,并且它仍然是可访问的。谢谢+1用于在分配之前在类范围内声明它们,使跟踪类范围的内容变得更加容易。