350 of 410 menu

The __isset Method

The __isset method is a magic method in PHP that is called when attempting to check the existence of an object property using the isset or empty functions, when that property is inaccessible or does not exist. The method accepts one parameter - the name of the property being checked.

Syntax

public function __isset(string $name): bool

Example

Let's create a class with the magic method __isset:

<?php class User { private $data = [ 'name' => 'John', 'age' => 30 ]; public function __isset($name) { return isset($this->data[$name]); } } $user = new User(); var_dump(isset($user->name)); var_dump(isset($user->email)); ?>

Code execution result:

true false

Example

Usage with dynamic properties:

<?php class DynamicProperties { private $storage = []; public function __isset($name) { return array_key_exists($name, $this->storage); } public function __set($name, $value) { $this->storage[$name] = $value; } } $obj = new DynamicProperties(); $obj->test = 'value'; var_dump(isset($obj->test)); var_dump(isset($obj->unknown)); ?>

Code execution result:

true false

See Also

  • the __get method,
    which is called when reading inaccessible properties
  • the __set method,
    which is called when writing to inaccessible properties
  • the __unset method,
    which is called when deleting inaccessible properties
byenru