[英]Defining global (dynamic) variables in Codeigniter
Is there a way of defining a dynamic global variable in Codeigniter? 有没有办法在Codeigniter中定义动态全局变量? I need to regularly use:
我需要经常使用:
$this->session->userdata('user_id')
in my code, and I really don't want to have to type this out all the time. 在我的代码中,我真的不想一直打出来。 What I've done in another project is use something like:
我在另一个项目中所做的是使用类似的东西:
$this->mid = $this->session->userdata('user_id')
in a controller's constructor, making it accessible for every method in that controller, but I then have to redefine it in every other controller constructor. 在控制器的构造函数中,使其可以访问该控制器中的每个方法,但我必须在每个其他控制器构造函数中重新定义它。 I know I sound lazy, but I just want to make the best DRY code possible.
我知道我听起来很懒,但我只想制作最好的DRY代码。 I know you can specify static variables in the config/config.php file, but these variables are dynamic - so I don't think you'll have access to the $this object (or something) in that file.
我知道你可以在config / config.php文件中指定静态变量,但这些变量是动态的 - 所以我认为你不能访问该文件中的$ this对象(或其他东西)。
Is there anyway of making such a session variable global? 有没有把这样的会话变量全局化?
Create a custom controller MY_Controller.php: 创建自定义控制器MY_Controller.php:
<?php
class MY_Controller extends Controller {
var user_id = '';
function __construct() {
parent::__construct();
$this->user_id = $this->session->userdata('user_id');
}
}
?>
And extend that controller by your controllers, for example the controller Welcome.php: 并通过控制器扩展该控制器,例如控制器Welcome.php:
<?php
class Welcome extends MY_Controller {
function __construct() {
parent::__construct();
}
function index() {
var_dump( $this->user_id );
}
}
?>
You can set the global variable in MY_Controller and use it on every controller that extends the custom one. 您可以在MY_Controller中设置全局变量,并在扩展自定义变量的每个控制器上使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.