PHP/CodeIgniter - 在__construct()中设置变量,但不能从其他函数访问它们

Jac*_*ack 6 php variables scope codeigniter

我很高兴有一个变量范围问题.也许我只需要更多咖啡......

这是我的(简化)代码 - 这是在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');
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我运行索引函数时,我被告知:

A PHP Error was encountered

Severity: Notice
Message: Undefined variable: agent
Filename: controllers/agent.php
Line Number: 51
Run Code Online (Sandbox Code Playgroud)

第51行是索引函数的第一行.出了什么问题?这是范围问题还是其他问题?

谢谢!

Dun*_*zzz 13

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

$this->User   = $this->my_auth_library->get_user();
$this->Agent  = $this->agent_model->get_agent($user->id);
Run Code Online (Sandbox Code Playgroud)

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


ian*_*ker 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以设置并使用它们 $this->agent