What is the purpose of "Get Instance" in Codeigniter? How would you explain this to a total beginner?
2 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. ;-)

- 30,334
- 10
- 78
- 137

- 30,637
- 12
- 78
- 117
-
22 pints, eh? Then what is the usefullness of a library/helper? Why not just use models? – Kevin Brown May 12 '10 at 14:38
-
3Of course seeing as everything is a PHP class you CAN put whatever you like wherever you like. Generally speaking in CodeIgniter it is broken down as "database interaction/business logic" = models, simple functions go in helpers and general classes are libraries. – Phil Sturgeon May 13 '10 at 08:07
-
@PhilSturgeon great explanation :) – Muhammad Zaman Apr 11 '18 at 12:48
-
Would expect anything less than 2 pints from Phil :-D – jminkler Dec 03 '18 at 21:49
It's an implementation of the singleton pattern. Essentially, there is only one instance of the class in question, which is designed to be accessible globally. The get_instance
method is static and so provides a way of accessing the instance from anywhere in your code.

- 32,488
- 9
- 84
- 95
-
2
-
7@Kevin: In that case I recommend you start reading about object-oriented programming (OOP) before delving into a framework that relies upon it! – Will Vousden May 12 '10 at 15:09