In previous PHP5 OOPS tutorial on PHP5 Tutorial – Magic Methods – __get() and __set(), we learnt how and when to use these magic methods.
This PHP5 OOPS tutorial will teach you how and when to use the magic methods __isset() and __unset().These methods are automatically called internally when isset() and unset() is called on undeclared data members. The magic method __isset() method receives an argument – the value of which is the name of the variable that the program wants to test if the variable is set or not.
The magic method __unset() method receives an argument – the value of which is the name of the variable that the program wants to unset.
Look at the example below:
class Customer { private $data = array(); public function __set($dt, $vl) { $this->data[$dt] = $vl; } public function __get($dt) { return $this->data[$dt]; } public function __isset($dt) { return isset($this->data[$dt]); } public function __unset($dt) { return unset($this->data[$dt]); } } $c = new Customer(); $c->name = "Hiren Prajapati"; echo isset($c->name)."\n"; echo unset($c->name);
In the above example the script creates a new Customer Object. The program assigns a string value to an undeclared variable i.e. $c->name. The undeclared variable is handled by the magic method __set(). Read this post on PHP5 Magic Methods __set() if you need more understanding how the magic method __set() works.Similarly, when the program calls unset() on the undeclared variable i.e. $c->name, the PHP5 magic method __unset() is invoked that takes the name of the undeclared variable i.e. “name” and unsets the internal array $data["name"].
The program ties to check if the undeclared variable i.e., $c->name has been set or not using the PHP method isset(). Since $c->name is an undeclared variable the PHP5 magic method __isset() is invoked that takes the name of the undeclared variable i.e. “name” and checks if the internal array $data["name"] is set or not.
No comments:
Post a Comment