Search code examples
phpmagic-methodsunset

PHP Magic Method __unset() does not work on calling unset function


I could not understand why __unset() not work.

class myclass {
    public $name = array();

    public function __set($arraykey, $value){
        $this->name[$arraykey] = $value;
    }

    public function __isset($argu){
        return isset($this->name[$argu]);
    }

    public function __unset($argu){ 
        echo "Working: Unset $this->name[$argu]";
        unset($this->name[$argu]);
    }
}

$obj = new myclass;
$obj->name = 'Arfan Haider';

var_dump(isset($obj->name));

unset($obj->name);

I read that whenever the unset() function is called, then Magic Method __unset() automatically is called and unsets the variable.

In above code I am using unset but it does not call __unset(). Why? Am I missing something in understanding the Magic Method __unset()?


Solution

  • The magic methods __set, __get, __isset and __unset only get called when accessing inaccessible properties. That means either private properties, protected properties (accessed outside of a child class) or properties which haven't been created.

    Calling your internal variable $_name instead of $name, or setting $name to private or protected instead of public will fix your problem.

    Note:

    You should only use protected properties or functions when they need to be accessible from an extending class - don't use it just because.