explain $CI =& get_instance();

04/23/2020 21:30:01

Looking through codeigniter's source code,

in its helper functions I keep seeing code $CI =& get_instance(); can anyone please explain to me how this code works?

I get that it is returning a reference to the $CI super object, but where does get_instance() come from?

Verified Answer (72 Votes)

01/20/2011 01:47:22

It's basically a Singleton Design Pattern that uses a function instead of a static method.

To look deeper, check out the source code

So basically, it doesn't enforce the singleton, but it's a shortcut to a public function...

Edit: Actually, now I understand. For PHP4 compatibility they had to do a double-global-variable-hack to get it to return the references properly. Otherwise the references would get all screwed up. And since PHP4 didn't have support for static methods (well, properly anyway), using the function was the better way. So it still exists for legacy reasons...

So if your app is PHP5 only, there should be nothing wrong with doing CI_Base::get_instance(); instead, it's identical...


Answer #2 (19 Votes)

01/20/2011 01:46:07

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.

I'm pretty sure it's defined in base.php or something similar.


Answer #3 (5 Votes)

04/28/2017 13:38:18

Only the class that extends CI_Controller,Model,View can use


Your Custom Class cannot use the above code. To use the above features in your custom class, your must use

$CI=&get instance();

for example,in your custom class

// this following code will not work
Class Car

//this will work
Class Car
// Here $CI is a variable.
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.