These magic methods let you control what happens when you read or write properties that don't exist or are not accessible in an object.
0
0
__get and __set for property access in PHP
Introduction
You want to handle reading a property that is private or missing without errors.
You want to control or customize what happens when someone sets a property value.
You want to create flexible objects that can store data dynamically.
You want to add logging or validation when properties are accessed or changed.
Syntax
PHP
public function __get(string $name) { // code to return a value for $name } public function __set(string $name, $value): void { // code to set $value for $name }
__get is called automatically when reading a property that is not accessible.
__set is called automatically when writing to a property that is not accessible.
Examples
This example stores unknown properties in an internal array and retrieves them.
PHP
<?php class Example { private $data = []; public function __get(string $name) { return $this->data[$name] ?? null; } public function __set(string $name, $value): void { $this->data[$name] = $value; } } $obj = new Example(); $obj->color = 'red'; echo $obj->color; ?>
This example uses __get and __set to access a private property safely.
PHP
<?php class Person { private $name = 'Alice'; public function __get(string $name) { if ($name === 'name') { return $this->name; } return null; } public function __set(string $name, $value): void { if ($name === 'name') { $this->name = $value; } } } $p = new Person(); echo $p->name; // reads private property via __get $p->name = 'Bob'; // sets private property via __set echo $p->name;
Sample Program
This program shows how __get and __set work by printing messages when properties are accessed or set. It stores values in an internal array.
PHP
<?php class MagicBox { private $items = []; public function __get(string $key) { echo "Getting '$key'\n"; return $this->items[$key] ?? 'Not found'; } public function __set(string $key, $value): void { echo "Setting '$key' to '$value'\n"; $this->items[$key] = $value; } } $box = new MagicBox(); $box->fruit = 'apple'; echo $box->fruit . "\n"; echo $box->vegetable . "\n";
OutputSuccess
Important Notes
If you try to access a property that exists and is public, __get and __set are not called.
Use __get and __set carefully because they can hide bugs if properties are misspelled.
Summary
__get and __set let you control reading and writing of inaccessible or missing properties.
They help make flexible and dynamic objects.
Remember to handle missing properties gracefully inside these methods.