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
public 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
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:
Attempting to unset 'a'
Attempting to unset 'c'
Example
Using __unset
to control access to private properties:
<?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:
Exception: Cannot unset private property 'email'