Codeigniter模块类中的全局变量未定义


Global vars in Codeigniter Module Class undefined

我在代码点火器模块控制器中有以下代码:

class MyClass extends MX_Controller{
    public $description = "index";
    public function index(){
        global $description;
        echo $description;
    }
}

根据正常的PHP规则和PHP文档,这应该可以工作。然而,事实并非如此。

如果我省略了global $description,我会注意到变量是undefined,但有了它,它似乎不会返回任何内容。

为什么global variables在这种情况下不起作用?

您应该这样做,而不是使用全局。这将在您处于类范围内时起作用所以你需要$this

class MyClass extends MX_Controller{
    public $description = "index";
    public function index(){
        echo $this->description;
    }
}

您可以通过以下方式设置变量:

$this->load->vars($global_variables_array);

其中$global_variables_array是关联键值对数组,描述为:-

此函数以关联数组作为输入,并使用PHP提取函数生成变量。该函数产生的结果与使用上面$This->load->view()函数的第二个参数相同。您可能希望独立使用此函数的原因是,如果您希望在控制器的构造函数中设置一些全局变量,并使它们在从任何函数加载的任何视图文件中可用。您可以多次调用此函数。数据被缓存并合并到一个数组中,以便转换为变量。

这是链接