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

标签 php codeigniter variables scope

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

这是我的(简化的)代码 - 这是在 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 行是索引函数的第一行。出了什么问题?这是范围问题还是其他问题?

谢谢!

最佳答案

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

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

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

关于PHP/CodeIgniter - 在 __construct() 中设置变量,但它们不能从其他函数访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147555/

相关文章:

codeigniter - 如何从 codeigniter 中的另一个 Controller 调用 Controller ?

json - 如何在 jq 的 "join"函数中使用换行符 (\n) 和制表符 (\t) 等非显示字符

ruby - 如何在 Ruby 类之间传递变量?

php - 过滤多对多关系 - Laravel

php - 如何查看上传的文件类型是pdf

mysql - Codeigniter:创建数据库后插入数据时出现 "Table not found"错误

javascript - 使用 JavaScript 将全局变量调用到两个函数中

php - Laravel 8 从 AWS S3 Buckets 下载文件

php - 如何在单击单选按钮时插入数据 - jquery/php/mysql?

php - 背景切换器?