__get and __set in PHP: How They Work and When to Use
__get and __set are PHP magic methods that let you control what happens when you read or write to inaccessible or undefined object properties. __get runs when you try to read a property that is private, protected, or doesn't exist, while __set runs when you try to assign a value to such a property.How It Works
Imagine your object as a box with some locked compartments (private or protected properties). Normally, you can't open these compartments directly. But with __get and __set, you create a special helper that listens whenever someone tries to peek inside or put something in these locked compartments.
When you try to read a property that is not accessible or doesn't exist, PHP automatically calls the __get method. Similarly, when you try to assign a value to such a property, PHP calls the __set method. This lets you decide what to do, like returning a default value, logging access, or storing data differently.
These methods act like a gatekeeper or a smart assistant, controlling how your object's hidden data is accessed or changed without exposing the actual properties directly.
Example
This example shows a class with private properties. When you try to get or set these properties from outside, the __get and __set methods handle the access and update.
<?php class Person { private $data = []; public function __get($name) { if (array_key_exists($name, $this->data)) { return $this->data[$name]; } return "Property '$name' not found."; } public function __set($name, $value) { $this->data[$name] = $value; } } $person = new Person(); $person->name = "Alice"; // Calls __set echo $person->name . "\n"; // Calls __get, outputs: Alice echo $person->age . "\n"; // Calls __get, outputs: Property 'age' not found.
When to Use
Use __get and __set when you want to control access to properties that are private or do not exist explicitly. This is helpful for:
- Creating flexible objects that can store dynamic properties without declaring them all upfront.
- Implementing read-only or write-only properties by controlling what happens on get or set.
- Adding validation, logging, or transformation when properties are accessed or changed.
- Hiding internal data structure and providing a clean interface.
For example, in a user profile class, you might want to store extra info without changing the class structure, or you want to check values before saving them.
Key Points
__getis triggered on reading inaccessible or undefined properties.__setis triggered on writing to inaccessible or undefined properties.- They allow flexible and controlled access to object data.
- Useful for dynamic properties, validation, and hiding internal details.
- Overusing them can make code harder to understand, so use wisely.
Key Takeaways
__get and __set let you control access to private or undefined properties in PHP objects.