CodeIgniter Forums
& get_instance() vs $this - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: & get_instance() vs $this (/showthread.php?tid=68202)



& get_instance() vs $this - rahulemaity - 06-08-2017

When should we use $this and when & get_instance()?I have a library file .The code is
class Test {

public function testf()
{
    echo 1;
}
}
Now I load the library in my controller function
$this->load->library('test');

Now in my view if we write $this->test->testf();.We get result 1;
Now the fact is I load the library in view file.Then it give error Undefined property: CI_Loader.
if we create an instance in view then its woking properly.like 
$ci=& get_instance();
$ci->loadl->library('test');
$ci->test->testf();
then it gives result 1;
My question is where to use $this and where to & get_instance();


RE: & get_instance() vs $this - NickOver - 06-08-2017

When you use =&get_instance() you pass object by reference. Thats mean you don't create a new object, you only operate on existing object.
You MUST use get_instance() if u want model object or library object in for example another library. In controller you extend CI_controller, in __construct() it use get_instance() so you have access to created instances of model, libraries or something else.


RE: & get_instance() vs $this - skunkbad - 06-08-2017

$this:

Refers to the current class. Only used in classes that are instantiated, meaning not in static classes. Static classes use "self".

$CI =& get_instance();

$CI is the CodeIgniter super object. All classes loaded though the CI Loader end up being usable through the super object. The super object is more or less a "service locator".

Special Note:

It happens that when in a controller or model, the controller or model has access to the CodeIgniter super object through $this. It may seem confusing, but that's why your controllers extend CI_Controller, and your models extend CI_Model.