In Codeigniter, get_instance()
is a globally available function that returns the Controller super-object which contains all the currently loaded classes (it ret
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...
get_instance()
every time you use the helper rather than storing its result in a variable.I prefer uses this way, it's simple
class Test
{
//magic method __get, whit this can use $this->load
//instead create a variable ci, then do $this->ci->load, cool :)
public function __get($var)
{
return get_instance()->$var;
}
public function showUrl()
{
$this->load->helper("url");
echo base_url();
}
}
Method chaining is not supported in PHP4
and CI
dropped support for PHP4
very recently (from version 2.0.0
). Also it's easy to write $CI
than writing get_instance()
every time.
Getting the result of get_instance()
by reference just makes no sense since PHP5. Sadly this bad habit seems to be deep-rooted, so let's just deal with it.
For those interested, here's an über fast instance getter:
function CI()
{
static $CI;
isset($CI) || $CI = CI_Controller::get_instance();
return $CI;
}
Note that the static variable wouldn't work if it were assigned by reference.
Also, you are forced not to get by reference the result of this CI()
. Extra sugar :-)
Ah, and obviously you still have the (slight) cost of the function call. You still may want to use a variable instead of calling the function dozens of times.
It could be a combination of several things, including the already mentioned:
Preferably, I like the idea of this 'recommendation' as being a part of a style guide. Maybe not the official style guide of CI, but still.
Imagine that all third-party scripts for CI implements this recommendation, any developer would be able to quickly determine how these scripts are designed - although this just being a very small part of the script.
Another thing that IMO is important is the mechanics of method chaining - and doing CI()->class->method()
wouldn't seem intuitive for me, knowing how the rest of CI works.
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