Welcome Guest, Not a member yet? Register   Sign In
& get_instance() vs $this
#1

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();
Reply
#2

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.
Reply
#3

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




Theme © iAndrew 2016 - Forum software by © MyBB