Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?php class MagicBox { private array $data = []; // __set: called when assigning to inaccessible property public function __set(string $name, mixed $value): void { echo "__set: $name = " . var_export($value, true) . " "; $this->data[$name] = $value; } // __get: called when reading an inaccessible property public function __get(string $name): mixed { echo "__get: $name "; return $this->data[$name] ?? null; } // __isset: called by isset() / empty() on inaccessible property public function __isset(string $name): bool { return isset($this->data[$name]); } // __unset: called by unset() on inaccessible property public function __unset(string $name): void { unset($this->data[$name]); } // __toString: called when object is cast/echoed as string public function __toString(): string { return json_encode($this->data, JSON_PRETTY_PRINT); } // __invoke: called when object is used as function public function __invoke(string $key): mixed { return $this->data[$key] ?? null; } } $box = new MagicBox(); $box->name = 'Alice'; // calls __set $box->email = 'alice@example.com'; echo $box->name; // calls __get echo isset($box->email) ? 'set' : 'not set'; // calls __isset echo $box; // calls __toString echo $box('name'); // calls __invoke
Result
Open