Using __unset()
The __unset()
 magic method is triggered by calling the unset()
 language constructs on inaccessible properties. The method accepts a single parameter, as per the following synopsis:
public bool __unset(string $name)
The $name
argument is the name of the property being interacted with.
Let's take a look at the following object context example:
<?php class User { private $data = [ 'name' => 'John', 'age' => 34, ]; public function __unset($name) { unset($this->data[$name]); } } $user = new User(); var_dump($user); unset($user->age); unset($user->salary); var_dump($user);
The User
class declares a single private $data
array property, alongside the __unset()
magic method. The method itself is quite simple; it merely calls for the unset()
passing it the value at a given array key. We are trying to unset to the $age
and $salary
properties here. The $salary
 property does not really exist, neither as a class property nor as a data
array key....