Before we dive in __isset() magic method. Let's see what isset() function does.


$name = 'devpeel';

var_dump(isset($name));

In case of isset() function, it will var dump true as the name variable exists. But why do we need __isset() magic method, lets find out.

Simple Example (Checking Properties)

class DevPeel
{

	protected $name = 'devpeel';

	public function __isset($key){
		return property_exists($this, $key);
	}
}

$class = new DevPeel();

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

Here, we’re simply using __isset() magic method inside of our DevPeel class & looking for a $key in the class. Here we want to check if a particular property has been set inside of DevPeel class. Let’s say we’re checking name property is being set in the DevPeel class or not.

It will result in bool(true) but if we try to run isset method directly on a protected property, it will show bool(false). That’s where __isset() method comes into play. Here we’re checking if the property exists in the class whether its public or protected, it’ll return accordingly.

Another Example (Validating Collections of Data)

Well __isset() magic method isn’t useful for protected properties only. Let’s look at this next example for more understanding of this magic method.

class User
{
	protected $data = [
		'email'=>'[email protected]'
	];

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

$user = new User();

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

Here we’re checking if the particular $key exists in the collection of data inside of our class and using isset function internally of __isset() magic method to check if the $key exists.

You may also Like