W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
有些時(shí)候,你可能想在你的控制器之外新建一些類,但同時(shí)又希望 這些類還能訪問(wèn) CodeIgniter 的資源。下面你會(huì)看到,這其實(shí)很簡(jiǎn)單。
get_instance()
| 返回: | Reference to your controller's instance |
| 返回類型: | CI_Controller |
任何在你的控制器方法中初始化的類都可以簡(jiǎn)單的通過(guò) get_instance() 函數(shù)來(lái)訪問(wèn) CodeIgniter 資源。這個(gè)函數(shù)返回一個(gè) CodeIgniter 對(duì)象。
通常來(lái)說(shuō),調(diào)用 CodeIgniter 的方法需要使用 $this
$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
// etc.
但是 $this 只能在你的控制器、模型或視圖中使用,如果你想在 你自己的類中使用 CodeIgniter 類,你可以像下面這樣做:
首先,將 CodeIgniter 對(duì)象賦值給一個(gè)變量:
$CI =& get_instance();
一旦你把 CodeIgniter 對(duì)象賦值給一個(gè)變量之后,你就可以使用這個(gè)變量 來(lái) 代替 $this
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.
如果你在類中使用get_instance()
函數(shù),最好的方法是將它賦值給 一個(gè)屬性 ,這樣你就不用在每個(gè)方法里都調(diào)用 get_instance() 了。
例如:
class Example {
protected $CI;
// We'll use a constructor, as you can't directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function foo()
{
$this->CI->load->helper('url');
redirect();
}
public function bar()
{
$this->CI->config->item('base_url');
}
}
在上面的例子中, foo() 和 bar() 方法在初始化 Example 類之后都可以正常工作,而不需要在每個(gè)方法里都調(diào)用 get_instance() 函數(shù)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: