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

phppublic function __isset(string $name): bool

Example

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

php<?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:

phptrue
false

Example

Usage with dynamic properties:

php<?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:

phptrue
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