PHP Magic Method __unset() does not work on calling unset function -
i 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 whenever unset() function called, magic method __unset() automatically called , unsets variable.
in above code using unset not call __unset(). why? missing in understanding magic method __unset()?
the magic methods __set, __get, __isset , __unset called when accessing inaccessible properties. means either private properties, protected properties (accessed outside of child class) or properties haven't been created.
calling internal variable $_name instead of $name, or setting $name private or protected instead of public fix problem.
note:
you should use protected properties or functions when need accessible extending class - don't use because.
Comments
Post a Comment