Php 为HMVC codeigniter设置全局变量
我是codeigniter的新手。 我想为我的助手、模型和控制器设置一个全局变量。 变量正在从数据库获取 以下是一个例子: 不知道将变量放在哪里Php 为HMVC codeigniter设置全局变量,php,codeigniter,Php,Codeigniter,我是codeigniter的新手。 我想为我的助手、模型和控制器设置一个全局变量。 变量正在从数据库获取 以下是一个例子: 不知道将变量放在哪里 $this->load->model('test'); $data = $this->test->get_code(); $this->code = $data["code"]; //main global variable 我的助手 function test() { if($this->code=
$this->load->model('test');
$data = $this->test->get_code();
$this->code = $data["code"]; //main global variable
我的助手
function test() {
if($this->code=="test") {
}
}
function index() {
echo $this->code;
}
我的控制器
function test() {
if($this->code=="test") {
}
}
function index() {
echo $this->code;
}
我的型号
function get_data() {
$query = $this->db->get_where('my_table', array('code' => $this->code));
return $query->row_array();
}
正如您在上面看到的脚本一样,$this->code
几乎用于我的助手
,我的控制器
,以及我的模型
。
我应该把变量放在哪里,这样我就可以通过只对所有人使用
$this->code
来访问变量 您可以将MY_控制器装箱到application/core文件夹中的extends MX_Controller中,并将MY_控制器装箱到application/module中创建您自己的控制器。例如,请参见下文
class MY_Controller extends MX_Controller {
public $code = ""; // Global variable
public function __construct() {
parent::__construct();
$this->load->model('test');
$data = $this->test->get_code();
$this->code = $data["code"]; //main global variable
}
}
class Admin extends MY_Controller {
function index() {
echo $this->code;
}
}
您可以将MY_控制器装箱到application/core文件夹中的extends MX_Controller中,并将MY_控制器装箱到application/module中创建您自己的控制器。例如,请参见下文
class MY_Controller extends MX_Controller {
public $code = ""; // Global variable
public function __construct() {
parent::__construct();
$this->load->model('test');
$data = $this->test->get_code();
$this->code = $data["code"]; //main global variable
}
}
class Admin extends MY_Controller {
function index() {
echo $this->code;
}
}
尝试将数据放入会话:
$this->load->model('test');
$data = $this->test->get_code();
$this->load->library('session');
$this->session->set_userdata('name' => $data );
及
您可以在每个函数中使用无负载会话,
外接程序config/autoload.php
$autoload['libraries'] = array('session');
尝试将数据放入会话:
$this->load->model('test');
$data = $this->test->get_code();
$this->load->library('session');
$this->session->set_userdata('name' => $data );
及
您可以在每个函数中使用无负载会话,
外接程序config/autoload.php
$autoload['libraries'] = array('session');
这是控制器专用的吗?那么助手和模型呢?助手不是必需的。您可以在MY_controller和model中设置方法,使用与autoload.php中的所有加载模型相同的方法,并在任意位置使用。但我需要控制器和模型的
function test()
helper。自动加载?我有很多模型必须在全局变量中使用。如果我将所有模型加载到自动加载,这是正确的方法吗?您不能在helper中使用控制器全局变量,所以您可以在my_conteroller中创建test()方法,如果您有仅用于控制器的扩展,则用于所有控制器?那么助手和模型呢?助手不是必需的。您可以在MY_controller和model中设置方法,使用与autoload.php中的所有加载模型相同的方法,并在任意位置使用。但我需要控制器和模型的function test()
helper。自动加载?我有很多模型必须在全局变量中使用。如果我将所有模型加载到自动加载,这是正确的方法吗?您不能在helper中使用控制器全局变量,因此您可以在my_conteroller中创建test()方法,并在extendsTry使用单独库中的代码时用于所有控制器?@Hekmat如何使用它?尝试在单独库中使用代码?@Hekmat如何使用它?