$ this is used when you create a new instance of the object.
For example, imagine this:
class Test { private $_hello = "hello"; public function getHello () { echo $this->_hello; // note that I removed the $ from _hello ! } public function setHello ($hello) { $this->_hello = $hello; } }
To access the getHello method, I have to create a new instance of the Test class, for example:
$obj = new Test (); // Then, I can access to the getHello method : echo $obj->getHello (); // will output "hello" $obj->setHello("lala"); echo $obj->getHello (); // will output "lala"
In fact, $ this is used inside the class when this is not possible. This is called an area .
Inside your class, you use $ this (to access * $ _ hello *, for example), but outside the class, $ this does NOT apply to elements inside your class (e.g. * $ _ hello *), this is what $ obj does.
Now the main difference between $ obj and $ is that $ obj gets access to your class from outside , some restrictions occur: if you define something private or protected in your class, for example, my variable * $ _ hello *, $ obj CANNOT access it (it's private!), but $ this can becase $ this to leave inside the class.
Cyril N.
source share