Session 代码点火器:设置';全局变量';
如果我想设置一个我的整个控制器都可以访问的变量,我该怎么做 现在,在我设置的每个函数中Session 代码点火器:设置';全局变量';,session,codeigniter,variables,Session,Codeigniter,Variables,如果我想设置一个我的整个控制器都可以访问的变量,我该怎么做 现在,在我设置的每个函数中 $id = $this->session->userdata('id'); 我希望能够从任何函数访问$id,而不为每个控制器定义它。:) 如果有更好的办法,我洗耳恭听!我是个笨蛋 仅在构造函数中定义该行要详细说明,您需要执行以下操作: class yourController extends Controller { // this is a property, accessible
$id = $this->session->userdata('id');
我希望能够从任何函数访问$id,而不为每个控制器定义它。:)
如果有更好的办法,我洗耳恭听!我是个笨蛋 仅在构造函数中定义该行要详细说明,您需要执行以下操作:
class yourController extends Controller {
// this is a property, accessible from any function in this class
public $id = null;
// this is the constructor (mentioned by Koo5)
function __construct() {
// this is how you reference $id within the class
$this->id = $this->session->userdata('id');
}
function getID() {
// returning the $id property
return $this->id;
}
}
有关PHP和的更多信息,请参阅手册。希望有帮助 如果使用global表示单个控制器的范围,则上述答案是正确的。如果要从多个控制器访问变量,建议定义BaseController类,然后扩展普通控制器以从该BaseController继承:
class yourController extends BaseController {}
我一直在全局变量和方法中使用此方法。您也可以在控制器中使用此方法
function __construct() {
// this is how you reference $id within the class
DEFINE("userId",$this->session->userdata('id'));
}
并称之为:
function getID() {
// returning the $id property
return userId;
}
我得到“未定义变量”。你能提供更多的信息吗?你又救了我,科林。谢谢