Codeigniter:设置'全局变量'

时间:2010-08-04 18:16:51

标签: session codeigniter variables

如果我想设置一个我的整个控制器可以访问的变量,我该怎么办?

现在,我正在设置的每个功能

$id = $this->session->userdata('id');

我希望能够从任何函数访问$ id,无需为每个控制器定义它。 :)

如果有更好的方法,我全都耳朵!我是个菜鸟!

4 个答案:

答案 0 :(得分:4)

详细说明Koo5's response,你会想要做这样的事情:

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 propertiesconstructors的详细信息,请参阅手册。希望有所帮助!

答案 1 :(得分:1)

如果使用全局表示单个控制器的范围,则上述答案是正确的。如果你想从多个控制器访问变量,我建议定义一个BaseController类,然后扩展你的普通控制器继承那个BaseController:

class yourController extends BaseController {}

我一直使用这个全局变量和方法。

答案 2 :(得分:0)

仅在构造函数中定义该行

答案 3 :(得分:0)

您也可以在控制器中使用此方法

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;
}
相关问题