Use CodeIgniter Resources within Library

To access CodeIgniter’s native resources from inside your own library, use the get_instance() function. It returns the CodeIgniter super object, the same one you reach through $this inside a controller, so your library can load helpers, read config, or call any other class the framework has instantiated.

Note: get_instance() is a CodeIgniter 3.x (and earlier) technique. CodeIgniter 4 dropped the global super object. There you reach framework features through Services, such as service('session') or \Config\Services::session(), or by injecting the dependencies your class needs through its constructor. Everything below applies to CodeIgniter 3.x.

The $this Construct

Inside a controller, model, or view you call CodeIgniter’s classes through the $this construct:

$this->load->helper('url');
$this->load->library('session');

But $this only works in those three places. It is not available inside a class you wrote yourself, because that class is not a child of the CodeIgniter controller. This is where get_instance() comes in.

Getting the CodeIgniter Instance

Assign the super object to a variable, then use that variable in place of $this:

$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');

get_instance() always returns the one and only CodeIgniter instance, no matter where you call it from. The helpers and libraries you load through it are the same ones your controllers see.

Using It Inside a Library

Calling get_instance() at the top of every method gets repetitive. The idiomatic approach is to grab the instance once in the constructor, store it on a property, and reuse it across the class:

class Geolocation
{
    protected $CI;

    public function __construct()
    {
        // Cache the CodeIgniter super object once.
        $this->CI =& get_instance();
        $this->CI->load->library('session');
    }

    public function locate()
    {
        $ip = $this->CI->input->ip_address();
        // ... resolve $ip to a country ...
        $this->CI->session->set_userdata('country', $country);

        return $country;
    }
}

With the instance cached on $this->CI, the whole library can use CodeIgniter’s input, session, config, database, and every other resource, exactly as if you were writing inside a controller.

A Note on =&

You will often see the assignment written with an ampersand:

$CI =& get_instance();

This is a holdover from PHP 4, where objects were copied on assignment and the reference (=&) was needed to keep pointing at the original object. Since PHP 5, objects are always handled by reference, so $CI = get_instance(); behaves identically. The CodeIgniter user guide still writes =& for consistency and it does no harm, but it is no longer the load-bearing detail older tutorials made it out to be.

References