0
0
PHPprogramming~5 mins

__get and __set for property access in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: __get and __set for property access
O(1)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look at what repeats when we access or set properties.

  • Primary operation: Array key assignment and lookup inside __set and __get.
  • How many times: Each property access or set triggers one array operation.
How Execution Grows With Input

As the number of properties stored grows, each access or set still does one array operation.

Input Size (n)Approx. Operations per Access/Set
101
1001
10001

Pattern observation: Each property access or set takes about the same time, no matter how many properties exist.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we changed the internal storage from an array to a linked list? How would the time complexity of property access change?