The __unset() magic method does not come handy often but lets take a look at what it does.

Let’s see a very simple example to understand __unset() magic method.

Simple Example

As we’ve previously learned on how to set the data using __set() magic method and check if the specific data is set using __isset() magic method likeso,

class User 
{
	protected $data = [];

	public function __set($key,$value){
		$this->data[$key] = $value;
	}

	public function __isset($key){
		return isset($this->data[$key]);
	}

}

$user = new User();
$user->name = 'Usama Munir';

var_dump($user);
var_dump(isset($user->name));

Now what if we need to unset $user->name for some particular reasons. Well we can achieve this through __unset() magic method.


class User 
{
	protected $data = [];

	public function __set($key,$value){
		$this->data[$key] = $value;
	}

	public function __isset($key){
		return isset($this->data[$key]);
	}

	public function __unset($key){
		unset($this->data[$key]);
	}

}

$user = new User();
$user->name = 'Usama Munir';
unset($user->name);
var_dump($user);

Here we’ve used the unset method internally within the __unset() magic method to unset the key required to unset within the data collection.

You may also Like