2010-08-04 129 views
2

如果我想设置一个变量,我的整个控制器可以访问,我该怎么做?Codeigniter:设置'全局变量'

眼下,在每一个功能我设置

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

我希望能够从任何函数访问的$ id W/O定义它为每个控制器。 :)

如果还有更好的方法,我是所有的耳朵!我是小白人!

回答

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更多信息。希望有所帮助!

+0

你再次拯救了我,科林。谢谢! – 2010-08-04 21:08:39

+0

很高兴我能帮忙,凯文! – 2010-08-04 21:14:45

0

定义在一个构造非常行只

+1

我得到 “未定义的变量”。你能提供更多的信息吗? – 2010-08-04 19:11:47

1

如果与全球你的意思是单个控制器的范围,上述答案是正确的。如果你想从多个控制器访问的变量,我推荐定义一个BaseController类,然后扩展您的正常控制器从BaseController继承:

class yourController extends BaseController {} 

我用所有这一切都为全局变量和方法的时间。

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; 
}