Posted by Arjun Arjun on Sunday 6th May 2018, 1 minute read

Get CI's object instance using get_instance() method

How to CodeIgniter 3

In this post, I will show you how you can access the CI's instance object within your custom classes. You can utilize all of CodeIgniter's native resources using $this instance. But $this instance only works within your controllers, your models, and your views.

Get CI’s object instance using get_instance() method

If you would like to use CodeIgniter’s classes from within your own custom classes you can do so as follows:

First, assign the CodeIgniter object to a variable:

$CI =& get_instance();

Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:

$CI =& get_instance();

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

You’ll notice that the above get_instance() function is being passed by reference. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.