$this variable is a pointer to the object making the function call. $this variable is not avialable in static methods. We will learn more about static methods in the next series of tutorials.
Example:
class Customer { private $name; public setName($name) { $this->name = $name; } } $c1 = new Customer(); $c2 = new Customer(); $c1->setName(“Hirenâ€); $c2->setName(“Vishalâ€);
In the above example, $c1 and $c2 are two separate Customer objects. Each object has its own memory to store names. But if you see the function setName() is common. During run time, how can it make a difference as to which memory location to use to store the function values. Therefore, it uses the $this variable. As mentioned earlier, $this variable is a pointer to the object making a function call. Therefore when we execute $c1->setName(“Hiren”), $this in the setName() function is a pointer or a reference to the $c1 variable.
No comments:
Post a Comment