鍍金池/ 教程/ PHP/ 創(chuàng)建輔助類(lèi)
模型
歡迎來(lái)到 CodeIgniter
通過(guò) CLI 執(zhí)行 CodeIgniter
自動(dòng)載入資源
初探 CodeIgniter
創(chuàng)建核心系統(tǒng)類(lèi)
應(yīng)用程序流程圖
安裝指南
CodeIgniter 特性
應(yīng)用性能分析
web 頁(yè)面緩存
公共函數(shù)
安全
處理多環(huán)境
使用 CodeIgniter 庫(kù)
管理你的應(yīng)用程序
創(chuàng)建輔助類(lèi)
兼容性函數(shù)
開(kāi)始 CodeIgniter
視圖
視圖文件的 PHP 替代語(yǔ)法
結(jié)束語(yǔ)
靜態(tài)頁(yè)面
URI 路由
錯(cuò)誤處理
版本升級(jí)
創(chuàng)建新聞
CodeIgniter URL
讀取新聞
鉤子 - 擴(kuò)展系統(tǒng)核心
設(shè)計(jì)和架構(gòu)目標(biāo)
保留字
疑難解答
下載 CodeIgniter
模式-視圖-控制
輔助函數(shù)
控制器
創(chuàng)建適配器
PHP 開(kāi)發(fā)規(guī)范

創(chuàng)建輔助類(lèi)

在某些情況下,你可能需要開(kāi)發(fā)一個(gè)類(lèi),這個(gè)類(lèi)能使用控制器一部分功能。

get_instance()

  • 返回: 你的控制器實(shí)例的引用
  • 返回類(lèi)型: CI_Controller

在你的控制器方法中初始化的任何類(lèi),都可以訪(fǎng)問(wèn) CodeIgniter 原生資源,簡(jiǎn)單通過(guò)使用 get_instance() 函數(shù)。這個(gè)函數(shù)回傳 CodeIgniter 對(duì)象。

通常來(lái)說(shuō),調(diào)用任何 CodeIgniter 方法需要你使用 $this 結(jié)構(gòu):

$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
// etc.

然而,$this 僅能再你的控制器,數(shù)據(jù)模型,視圖中使用。如果你想在你的類(lèi)中使用 CodeIgniter 類(lèi),可以參考以下做法:

首先,將 CodeIgniter 對(duì)象賦值給變量:

$CI =& get_instance();

一旦你將對(duì)象賦值給變量,你可以使用變量實(shí)例取代 $this

$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.

如果在其他類(lèi)中使用 get_instance(),可以將它賦給一個(gè)屬性。通過(guò)這個(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() 方法將會(huì)在你實(shí)例化的子類(lèi)工作,不需要每次都調(diào)用 get_instance()

上一篇:安裝指南下一篇:web 頁(yè)面緩存