Source Code:
(back to article)
<?php class MyClass { private $data = []; public function __get($name) { // This magic method is called when a non-existent or inaccessible property is accessed. // The parameter $name contains the name of the property that was accessed. // The `array_key_exists()` function checks if the specified key exists in the array. // In this case, it checks if the property with the name specified in $name exists in the $data array. if (array_key_exists($name, $this->data)) { // If the property exists in the $data array, return its value. return $this->data[$name]; } } public function __set($name, $value) { // This magic method is called when a non-existent or inaccessible property is set. // The parameter $name contains the name of the property that was set, and $value contains its value. // The value of the property is stored in the $data array with the property name as the key. $this->data[$name] = $value; } } $obj = new MyClass(); $obj->foo = 'bar'; // Calls the __set() magic method, setting the 'foo' property to the value 'bar'. echo $obj->foo; // Calls the __get() magic method, retrieving the value of the 'foo' property and outputting it.
Result:
Report an issue