The __unset() magic method in PHP is automatically triggered when unset() is used on inaccessible or non-existent object properties. It allows developers to control how object data is removed, especially when working with dynamically stored properties.
unset() is called on an object property.__get() and __set().The __unset() method does not directly remove private or protected class properties unless explicitly programmed. Instead, it typically manages removal from internal storage like arrays.
// PHP class demonstrating __unset() magic method
<?php
class User {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __unset($name) {
if (isset($this->data[$name])) {
unset($this->data[$name]);
}
}
}
$user = new User();
$user->name = "Meghraj";
echo $user->name;
unset($user->name);
var_dump(isset($user->name));
?>
The property name is stored dynamically inside an array. When unset($user->name) is called, the __unset() method removes it safely, and isset() confirms that it no longer exists.
Try adding multiple dynamic properties such as email or age, then unset them one by one to observe how __unset() manages internal storage.
__get(), __set(), and __unset() for clean design.Product class using dynamic properties.__get(), __set(), and __unset().isset().