本文實例講述了CI框架附屬類用法。分享給大家供大家參考,具體如下:
有些時候,你可能想在你的控制器之外新建一些類,但同時又希望 這些類還能訪問 CodeIgniter 的資源
任何在你的控制器方法中初始化的類都可以簡單的通過 get_instance()
函數(shù)來訪問 CodeIgniter 資源。這個函數(shù)返回一個 CodeIgniter 對象。
通常來說,調(diào)用 CodeIgniter 的方法需要使用 $this
$this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url');
但是 $this
只能在你的控制器、模型或視圖中使用,如果你想在 你自己的類中使用 CodeIgniter 類,你可以像下面這樣做:
首先,將 CodeIgniter 對象賦值給一個變量:
$CI = get_instance();
一旦你把 CodeIgniter 對象賦值給一個變量之后,你就可以使用這個變量 來 代替 $this
$CI = get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url');
如果你在類中使用``get_instance()
`` 函數(shù),最好的方法是將它賦值給 一個屬性 ,這樣你就不用在每個方法里都調(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 類之后都可以正常工作,而不需要在每個方法里都調(diào)用 get_instance()
函數(shù)。
更多關(guān)于CodeIgniter相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《ThinkPHP入門教程》、《ThinkPHP常用方法總結(jié)》、《Zend FrameWork框架入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于CodeIgniter框架的PHP程序設(shè)計有所幫助。