explain $CI =& get_instance();

Hailwood picture Hailwood · Jan 19, 2011 · Viewed 86.8k times · Source

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?

Answer

ircmaxell picture ircmaxell · Jan 19, 2011

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...