您好,欢迎访问一九零五行业门户网

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 资源 的详细内容。
其它类似信息

推荐信息