duanbai1974 2011-08-22 12:36
浏览 51
已采纳

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

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!

  • 写回答

2条回答 默认 最新

  • dongsonglian7303 2011-08-22 12:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?