get_instance() in Codeigniter: Why assign it to a variable? get_instance() in Codeigniter: Why assign it to a variable? codeigniter codeigniter

get_instance() in Codeigniter: Why assign it to a variable?


As far as I know, it's a matter of convenience more than anything. Chances are that you will be using the CI super object a lot in your libraries so why not assign it to a variable to make it a little easier to work with?

There are a few other things to consider...

  1. If you put this method in a helper, that method becomes a dependency for any class you are using it in. This might not be a big deal for you, but if you want to share libraries with anyone else they may not be happy about the dependency, especially since there is already a standard way of handling this in the CI community.
  2. There is a slight impact on performance because you are calling get_instance() every time you use the helper rather than storing its result in a variable.
  3. Since this is a helper method that is supposed to save you time, for anyone who is working mostly in the core MVC files of CI, setting up a helper like this would take longer than just setting it to a variable in the few places you need it.


Why is it recommended to assign get_instance() to a variable rather than calling it directly?

Most probably, it is recommended to maintain backward compatibility with php4, where objects were not passed by reference by default, but were cloned.

Is there any reason not to take this approach?

Only if you want your application to run on outdated php installations


It is necessary to assign by reference because the value of CI_Controller::$instance is subject to change if another instance of the class is created. The constructor re-assigns self::$instance each time it runs.

In general, this feels like a bad design pattern and is missing the property of a singleton that limits the class to only one instance, http://en.wikipedia.org/wiki/Singleton_pattern.

It seems possible to type, CI_Controller::get_instance()->$className->$method(); which does seem like more typing that your requested CI()->$className->$method.

Ultimately, it would make sense to require that only one instance of $instance can be created and then the need for assigning by reference would be eliminated.