【发布时间】:2016-11-09 11:16:01
【问题描述】:
从早期的 CodeIgniter 到现在一直困扰着我的一个问题,随着新的 CI 3,我想看看是否有更优雅的方法来解决它。
// file: application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
public $GLO;
function __construct(){
parent::__construct();
$this->GLO['foo'] = 'bar';
$this->GLO['arr'] = array();
}
}
然后,在后面的代码中,我需要动态获取和设置 $GLO 变量的值。比如:
// file: application/controllers/dispatcher.php
class Dispatcher extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->model('public/langs');
print_r($this->GLO);
}
}
将打印正确的array('foo'=>'bar, 'arr'=>Array())。同样在我的模型中,我可以以相同的方式获取 $GLO 数组的值。但是,只要我需要在 $GLO 数组中设置任何值,我就会得到Indirect modification of overloaded property notice,所以我被卡住了。在我的模型中(执行数据库查询后):
// file: application/models/public/langs.php
class Langs extends CI_Model {
function __construct(){
parent::__construct();
}
function set_global_languages(){
print_r($this->GLO); // <<< prints the same values as in the controller above
$temp = array();
// [stripped db code]
$temp['label'] = $row->label;
$temp['id'] = $row->id;
$this->GLO['arr'][] = $temp; // <<< this is where the notice happens
}
关于如何使用$this->GLO['foo'] = 'baz'; 在我的模型中设置此全局数组的属性的任何线索?
干杯。
【问题讨论】:
-
MY_Controller GLO和CI_Model GLO是什么关系?我没听懂。
-
这个想法是在控制器中声明一个全局变量,并在应用程序的其他控制器和模型中使用它。 $this->GLO 应该在整个应用程序中引用同一个公共 $GLO。
-
但是您将其定义为 My_Controller 类范围。看起来这就是为什么您无法从模型范围内访问它的原因。查看更多关于类的信息,$this 变量。 $this 不是全局变量。
-
似乎我可以读取 var,但我无法设置 var - 尽管它在不同的范围内?嗯..
标签: php arrays codeigniter oop