PHP/CodeIgniter - Setting variables in __construct(), but they're not accessible from other functions

ⅰ亾dé卋堺 提交于 2020-01-12 19:05:10

问题


I'm happy a bit of a variable scoping problem. Maybe I just need more coffee...

Here's my (simplified) code - this is in 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');
}

Unfortunately, when I run the index function, I'm told:

A PHP Error was encountered

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

Line 51 is the first line of the index function. What's going wrong? Is this a scope issue or something else?

Thanks!


回答1:


You haven't set $agent in your index action, if you want variables set in the constructor accessible then you have to set them as a class property ie: $this->Agent = ...;, and access them in the same way with $this->Agent->id. (I would capitalise them to show that they are objects and not just variables) For example:

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

The constructor behaves the same as any other class methods, its only special property is that it's automatically ran when the class is instantiated, normal variable scope still applies.




回答2:


you need to define the variables outside the constructor, like this:

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');
    }
}

then you can set and get them using $this->agent



来源:https://stackoverflow.com/questions/7147555/php-codeigniter-setting-variables-in-construct-but-theyre-not-accessible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!