CodeIgniter - when to use get_instance()

How I learned when to use get_instance with CodeIgniter

If you are new to CodeIgniter you may be confused as to when you need to use get_instance and when you don't, it certainly tripped me up when I first came back to CodeIgniter after leaving the PHP community for some time.

Luckily it is pretty simple to remember.

If you are writing code that lives within a controller, a model or a view that is under CodeIgniter's control then you do not need to use get_instance.

If however you are writing your own custom libraries or something that sits outside of the MVC files then you do need to use it.

So, if you are inside a model you could do something like this;


But if you are in a class you have written yourself then the $this object will not know about the CodeIgniter stuff, so you would do something like this;

$ci=& get_instance();

We use =& because we don't want to make a new copy of the CodeIgniter object, we want to use the original one.

Recent posts View all


History of Ruby Programming Language

The history of the Ruby programming language - the essentials


What I look for in a CTO

There are eight things I always look for when deciding if someone would make a good CTO