__get and __set for property access in PHP - Time & Space Complexity
When using __get and __set in PHP, it's important to understand how accessing or setting properties affects performance.
We want to know how the time to access or set a property changes as the number of properties or operations grows.
Analyze the time complexity of the following PHP code using __get and __set.
class Example {
private array $data = [];
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
}
$obj = new Example();
$obj->foo = 'bar';
echo $obj->foo;
This code stores properties in an internal array and accesses them via magic methods.
Look at what repeats when we access or set properties.
- Primary operation: Array key assignment and lookup inside
__setand__get. - How many times: Each property access or set triggers one array operation.
As the number of properties stored grows, each access or set still does one array operation.
| Input Size (n) | Approx. Operations per Access/Set |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: Each property access or set takes about the same time, no matter how many properties exist.
Time Complexity: O(1)
This means accessing or setting a property using __get or __set takes a constant amount of time regardless of how many properties are stored.
[X] Wrong: "Accessing properties with __get and __set gets slower as more properties are added."
[OK] Correct: The internal array uses fast key lookup, so each access or set is quick and does not slow down with more properties.
Understanding how magic methods like __get and __set work helps you explain object behavior clearly and shows you know how PHP handles property access efficiently.
What if we changed the internal storage from an array to a linked list? How would the time complexity of property access change?