This article describes the usage of CI framework affiliate classes. Share it for your reference, as follows:
Sometimes you might want to create new classes outside your controller, but you also want them to access CodeIgniter's resources
Any class initialized in your controller method can be simply passedget_instance()
Functions to access CodeIgniter resources. This function returns a CodeIgniter object.
Generally speaking, the method that calls CodeIgniter needs to be used$this
$this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url');
but$this
Only available in your controller, model, or view, if you want to use the CodeIgniter class in your own class, you can do it like this:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
Once you assign the CodeIgniter object to a variable, you can use this variable instead.$this
$CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url');
If you use `` in classget_instance()
The best way to do a function is to assign it to a property so that you don't have to call it in every methodget_instance()
Now.
For example:
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'); } }
In the above example,foo()
andbar()
Methods work properly after initializing the Example class, without being called in each method.get_instance()
function.
For more information about CodeIgniter, readers who are interested in view the topic of this site:Codeigniter Introductory Tutorial》、《Advanced tutorial on CI (CodeIgniter) framework》、《Summary of excellent development framework for php》、《ThinkPHP Introduction Tutorial》、《Summary of common methods of ThinkPHP》、《Zend FrameWork framework tutorial》、《PHP object-oriented programming tutorial》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php》
I hope that this article will be helpful to everyone's PHP programming based on the CodeIgniter framework.