自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';
在模型中设置此全局数组的属性的任何线索?
干杯。
sintakonte,非常感谢您的提示。昨晚我不得不重写大量代码以查看其是否起作用以及如何起作用。注册表类按预期工作!这种set / get方法的唯一问题是对深层数组的处理,尤其是那些动态创建的数组以及它们的数据也被动态推送的数组。所以今天早上我做了一些非常糟糕的事情:),并创建了这个类:
class Globals {
public $data = array();
}
因此,现在我要从头开始$this->GLO['foo']
,$this->globals->data['foo']
并保持现有语法完整!这也使我可以在使用不同名称的不同控制器和模型中重用该类,一旦将其初始化为“ globals”,另一次初始化为“ admin”。似乎也可以正常工作!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句