Home > Article > Backend Development > 003 - CI uses CodeIgniter resources in your library
Use the get_instance() function in your class library to access CodeIgniter's native resource, this function returns the CodeIgniter super object.
Normally, in your controller method you would use $this to call all available CodeIgniter method:
$this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url'); // etc.
But $this can only be used directly in your controller, model or view, if You want to use in your own class CodeIgniter class, you can do the following:
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 to instead of $this
##
$CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url'); // etc.
Note:
You will see the above
get_instance() function by reference To pass:
$CI =& get_instance();This is very important, reference assignment allows you to use the original CodeIgniter object instead of creating it a copy.
Since the class library is a class, we'd better make full use of OOP principles. Therefore, in order to allow all methods in the class to use the CodeIgniter super object, it is recommended to assign it to An attribute:
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'); } }Related recommendations:
002 - Differences and options between PDO and MySQLi
001 - Detailed analysis of PDO usage
The above is the detailed content of 003 - CI uses CodeIgniter resources in your library. For more information, please follow other related articles on the PHP Chinese website!