PHP / CodeIgniter - 在__construct()中设置变量,但不能从其他函数访问 [英] PHP/CodeIgniter - Setting variables in __construct(), but they're not accessible from other functions
问题描述
我很高兴一个变量范围问题。也许我只需要更多的咖啡...
这是我的(简化)代码 - 这是在CodeIgniter 2:
class Agent extends CI_Controller {
public function __construct()
{
parent :: __ construct
$ this-> load-> model('agent_model');
//获取将在代理函数中常用的初始数据
$ 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');不幸的是,当我运行索引函数时,我被告知:
遇到PHP错误
严重性:注意
消息:未定义变量:代理
文件名:controllers / agent.php
行号:51
51行第一行的索引函数。出了什么问题?这是范围问题还是其他问题?
谢谢!
您尚未在索引操作中设置 $ agent
,如果您希望在构造函数中设置的变量可访问,则必须将它们设置为类属性ie: $ this-> Agent = ...;
,并以相同的方式使用 $ this-> Agent-> id
。 (我将它们大写,以表明它们是对象而不仅仅是变量)例如:
$ this-& $ this-> my_auth_library-> get_user();
$ this-> Agent = $ this-> agent_model-> get_agent($ user-> id);
构造函数的行为与任何其他类方法相同,它唯一的特殊属性是它会自动运行该类被实例化,正常的变量范围仍然适用。
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!
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.
这篇关于PHP / CodeIgniter - 在__construct()中设置变量,但不能从其他函数访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!