非常教程

Codeigniter 3参考手册

用户指南 | User guide: General

创建辅助类 | Creating Ancillary Classes

在某些情况下,您可能希望开发存在于控制器之外但能够利用CodeIgniter所有资源的类。你会看到,这是很容易实现的。

get_instance()

get_instance()

返回:

参考您的控制器的实例

返回类型:

是CI_Controller

您在控制器方法中实例化的任何类都可以通过使用该get_instance()函数访问CodeIgniter的本机资源。该函数返回主要的CodeIgniter对象。

通常,要调用任何可用的方法,CodeIgniter要求您使用$this建造:

$this->load->helper('url');
$this->load->library('session');
$this->config->item('base_url');
// etc.

$this但是,只在控制器、模型或视图中工作。如果您想在您自己的自定义类中使用CodeIgniter类,可以这样做:

首先,将CodeIgniter对象赋值给一个变量:

$CI =& get_instance();

一旦将对象赋值给变量,就会使用该变量相反$this*

$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
// etc.

如果你要用get_instance()在另一个类中,如果将其分配给属性,则会更好。这样,你就不用打电话了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()将在实例化示例类之后工作,而不需要调用get_instance()每个人。

Codeigniter 3

CodeIgniter 是一个PHP MVC框架,特点是超轻量级、有数据加密、有灵活URI路由等。对于 PHP 程序员来说,它小巧但功能强大。

主页 https://codeigniter.com/
源码 https://github.com/bcit-ci/CodeIgniter
版本 3
发布版本 3.1.5