php ci加载类库,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');

}

}

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值