在你的类库中使用 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');
}
}