導讀 跟大家講解下有關003 - CI在你的類庫中使用 CodeIgniter 資源 ,相信小伙伴們對這個話題應該也很關注吧,現在就為小伙伴們說說003 -
跟大家講解下有關003 - CI在你的類庫中使用 CodeIgniter 資源 ,相信小伙伴們對這個話題應該也很關注吧,現在就為小伙伴們說說003 - CI在你的類庫中使用 CodeIgniter 資源 ,小編也收集到了有關003 - CI在你的類庫中使用 CodeIgniter 資源 的相關資料,希望大家看到了會喜歡。
在你的類庫中使用 get_instance() 函數來訪問 CodeIgniter 的原生資源,這個函數返回 CodeIgniter 超級對象。
通常情況下,在你的控制器方法中你會使用 $this 來調用所有可用的 CodeIgniter 方法:
$this->load->helper('url');$this->load->library('session');$this->config->item('base_url');// etc.但是 $this 只能在你的控制器、模型或視圖中直接使用,如果你想在你自己的類中使用 CodeIgniter 類,你可以像下面這樣做:
首先,將 CodeIgniter 對象賦值給一個變量:
$CI =& get_instance();一旦你把 CodeIgniter 對象賦值給一個變量之后,你就可以使用這個變量來 代替 $this
$CI =& get_instance();$CI->load->helper('url');$CI->load->library('session');$CI->config->item('base_url');// etc.注解:
你會看到上面的 get_instance() 函數通過引用來傳遞:
$CI =& get_instance();這是非常重要的,引用賦值允許你使用原始的 CodeIgniter 對象,而不是創建一個副本。
然類庫是一個類,那么我們最好充分的使用 OOP 原則,所以,為了讓類中的所有方法都能使用 CodeIgniter 超級對象,建議將其賦值給一個屬性:
class Example_library { 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() { echo $this->CI->config->item('base_url'); }}相關推薦:
002 - PDO和MySQLi區別與選擇
001 - PDO 用法詳細解析
以上就是003 - CI在你的類庫中使用 CodeIgniter 資源 的詳細內容,更多請關注php中文網其它相關文章!
來源:php中文網