get set isset and unset
suggest change__get runs when code reads a property that is inaccessible or does not exist:
$animal = new Animal();
$height = $animal->height;
$name is "height". Writing an inaccessible or missing property like so:
$animal->height = 10;
invokes __set($name, $value), with $name equal to "height" and $value equal to 10. An existing public property is read and written directly, and these methods are not called.
isset() reports whether a variable is set, and unset() destroys a variable. Checking an object's property 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