Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter: Get Instance

Tags:

What is the purpose of "Get Instance" in Codeigniter? How would you explain this to a total beginner?

like image 658
Kevin Brown Avatar asked May 12 '10 13:05

Kevin Brown


People also ask

How can you access the CodeIgniter instance by reference?

get_instance() is a function defined in the core files of CodeIgniter. You use it to get the singleton reference to the CodeIgniter super object when you are in a scope outside of the super object.

What is instance in CodeIgniter?

Any class that you instantiate within your controller methods can access CodeIgniter's native resources simply by using the get_instance() function. This function returns the main CodeIgniter object.


1 Answers

Ok, so everything in CodeIgniter runs through the super-magic $this variable. This only works for classes, as $this basically defines the current class.

Your controller is a class, so $this is there, allowing you to do $this->load->model('whatever');

In models, you are also using a class. It is slightly different here, as $this only contains useful stuff as you are extending from Model. Still, $this is still valid.

When you are using a helper or a library, you need to find that "instance" or $this equivalent.

$ci =& get_instance(); 

…makes $ci contain the exact same stuff/code/usefulness as $this, even though you are not in a class, or not in a class that inherits it.

That's an explanation for total beginners after 2 pints, so it's either wrong or about right. ;-)

like image 179
Phil Sturgeon Avatar answered Sep 30 '22 13:09

Phil Sturgeon