【问题标题】:PHP/CodeIgniter - Setting variables in __construct(), but they're not accessible from other functionsPHP/CodeIgniter - 在 __construct() 中设置变量,但其他函数无法访问它们
【发布时间】:2011-08-22 12:36:20
【问题描述】:

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

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

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

A PHP Error was encountered

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

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

谢谢!

【问题讨论】:

标签: php codeigniter variables scope


【解决方案1】:

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

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

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

【讨论】:

  • 感谢评论解释这一点 - 我曾假设 __construct() 在函数之前“添加”它,它仍然可以访问。谢谢!
【解决方案2】:

你需要在构造函数之外定义变量,像这样:

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 设置和获取它们

【讨论】:

  • +1 用于在分配之前在类范围内声明它们,这使得跟踪类范围内的内容变得更加容易。
猜你喜欢
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2011-05-12
  • 1970-01-01
  • 2020-04-13
相关资源
最近更新 更多