2010-08-04 184 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; 
}