99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

CodeIgniter 創(chuàng)建附屬類

2018-07-21 15:37 更新

創(chuàng)建附屬類

有些時(shí)候,你可能想在你的控制器之外新建一些類,但同時(shí)又希望 這些類還能訪問(wèn) CodeIgniter 的資源。下面你會(huì)看到,這其實(shí)很簡(jiǎn)單。

get_instance()

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ù)。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)