The __unset Method

The __unset method is one of the magic methods in PHP. It is automatically called when trying to unset a non-existent or inaccessible object property using the unset function. The method accepts one parameter - the name of the property being attempted to unset.

Syntax

phppublic function __unset(string $name): void

Example

Let's create a class with the magic method __unset and try to unset a non-existent property:

php<?php
class MyClass {
  private $data = ['a' => 1, 'b' => 2];
  
  public function __unset($name) {
    echo "Attempting to unset '$name'\n";
    unset($this->data[$name]);
  }
}

$obj = new MyClass();
unset($obj->a);
unset($obj->c);
?>

Code execution result:

phpAttempting to unset 'a'
Attempting to unset 'c'

Example

Using __unset to control access to private properties:

php<?php
class User {
  private $email = 'user@example.com';
  
  public function __unset($name) {
    if ($name === 'email') {
      throw new Exception("Cannot unset private property 'email'");
    }
  }
}

$user = new User();
unset($user->email);
?>

Code execution result:

phpException: Cannot unset private property 'email'

See Also

  • the __set method,
    which is called when writing to an inaccessible property
  • the __get method,
    which is called when reading an inaccessible property
  • the __isset method,
    which is called when checking the existence of an inaccessible property