__isset and __unset

PHP 5.1.0 introduces the magic methods __isset and __unset. These methods are called indirectly by the built-in PHP functions isset and unset. The need for these magic methods results directly from the existence of magic set and get methods for undeclared data members. The magic method __isset will be called whenever isset is used with an undeclared data member.

Suppose you want to determine whether the name variable of your Person instance in Listing 13-1 has been set. If you execute the code isset($t->name);, the return value will be false. To properly check whether an undeclared data member has been set, you need to define an __isset method. Redo the code for the Person class to incorporate a magic __isset method (see Listing 13-2).

Listing 13-2. The Person class with a magic __isset method
class Person{
    protected $datamembers = array();
    private $declaredvar = 1;
    public function __set($variable, $value){
        //perhaps check value passed in
        $this->datamembers[$variable] = $value;
    }
    public function __get($variable){
        return $this->datamembers[$variable];
    }
    function __isset($name){
        return isset($this->datamembers[$name]);
    }
    function getDeclaredVariable(){
      return $this->declaredvar;
    }
}
$p = new Person();
$p->name = 'Fred';
echo '$name: '. isset($p->❶name). '<br />';//returns true $temp = $p->
getDeclaredVariable();
echo '$declaredvar: '. isset(❷$temp). '<br />';//returns true
true
					true
				

Calling isset against the undeclared data member ❶ name will return true because an implicit call is made to the __isset method. Testing whether ❷ a declared data member is set will also return true, but no call, implicit or otherwise, is made to __isset. We haven't provided an __unset method, but by looking at the __isset method you can easily see how an undeclared variable might be unset.

You have __isset and __unset methods only because there are magic set and get methods. All in all, in most situations, it seems simpler to forget about using undeclared data members, and thereby do away with the need for magic set and get methods and their companion __isset and __unset methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.6.194