← Back to Chapters

PHP OOP __unset() Magic Method

? PHP OOP __unset() Magic Method

? Quick Overview

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.

? Key Concepts

  • Automatically invoked when unset() is called on an object property.
  • Accepts the property name as a parameter.
  • Commonly paired with __get() and __set().
  • Ideal for managing dynamic properties stored in arrays.

? Syntax & Theory

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.

? Code Example

? View Code Example
// 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));
?>

? Live Output / Explanation

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.

? Interactive Concept

Try adding multiple dynamic properties such as email or age, then unset them one by one to observe how __unset() manages internal storage.

? Use Cases

  • Dynamic user profile systems
  • Data containers with runtime properties
  • ORM-style entity management
  • Flexible API response objects

✅ Tips & Best Practices

  • Always verify property existence before unsetting.
  • Use consistent internal storage for dynamic properties.
  • Combine __get(), __set(), and __unset() for clean design.

? Try It Yourself

  • Create a Product class using dynamic properties.
  • Implement __get(), __set(), and __unset().
  • Unset selected properties and verify with isset().