Home > Backend Development > PHP Tutorial > 003 - CI uses CodeIgniter resources in your library

003 - CI uses CodeIgniter resources in your library

不言
Release: 2023-03-23 10:10:02
Original
1135 people have browsed it


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.
Copy after login

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();
Copy after login

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.
Copy after login

Note:

You will see the above

get_instance() function by reference To pass:


$CI =& get_instance();
Copy after login

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');
    }

}
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template