PHP › Magic Methods
What do the __get and __set magic methods do, and how do they let you customize behavior when accessing properties that do not exist or are inaccessible?
BeginnerAnswer
The __get magic method is automatically called when code attempts to read an inaccessible or undefined property on an object, and __set is similarly called when attempting to write to such a property, letting you intercept these operations to implement custom behavior, such as computing a value dynamically, validating a value before storing it, or providing controlled access to otherwise private internal data.
class User {
private $data = [];
public function __get($name) { return $this->data[$name] ?? null; }
public function __set($name, $value) { $this->data[$name] = $value; }
}
$user = new User();
$user->email = 'ali@example.com';
echo $user->email;Real-world example A flexible configuration object uses __get and __set to dynamically store and retrieve any arbitrary configuration key without needing to explicitly declare a separate property for every possible setting in advance.