Looking for php Answers? Try Ask4KnowledgeBase
Looking for php Keywords? Try Ask4Keywords

PHP __get(), __set(), __isset() and __unset()


Example

Whenever you attempt to retrieve a certain field from a class like so:

$animal = new Animal();
$height = $animal->height;

PHP invokes the magic method __get($name), with $name equal to "height" in this case. Writing to a class field like so:

$animal->height = 10;

Will invoke the magic method __set($name, $value), with $name equal to "height" and $value equal to 10.

PHP also has two built-in functions isset(), which check if a variable exists, and unset(), which destroys a variable. Checking whether a objects field is set like so:

isset($animal->height);

Will invoke the __isset($name) function on that object. Destroying a variable like so:

unset($animal->height);

Will invoke the __unset($name) function on that object.

Normally, when you don't define these methods on your class, PHP just retrieves the field as it is stored in your class. However, you can override these methods to create classes that can hold data like an array, but are usable like an object:

class Example {
    private $data = [];

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

    public function __get($name) {
        if (!array_key_exists($name, $this->data)) {
            return null;
        }

        return $this->data[$name];
    }

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

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

$example = new Example();

// Stores 'a' in the $data array with value 15
$example->a = 15;

// Retrieves array key 'a' from the $data array
echo $example->a; // prints 15

// Attempt to retrieve non-existent key from the array returns null
echo $example->b; // prints nothing

// If __isset('a') returns true, then call __unset('a')
if (isset($example->a)) {
    unset($example->a));
}

empty() function and magic methods

Note that calling empty() on a class attribute will invoke __isset() because as the PHP manual states:

empty() is essentially the concise equivalent to !isset($var) || $var == false