__construct and __destruct in PHP - Time & Space Complexity
Let's see how the time cost changes when using __construct and __destruct methods in PHP classes.
We want to know how the program's work grows as we create more objects.
Analyze the time complexity of the following code snippet.
class Example {
public function __construct() {
// Initialization work
}
public function __destruct() {
// Cleanup work
}
}
for ($i = 0; $i < $n; $i++) {
$obj = new Example();
}
This code creates $n objects, each running __construct when made and __destruct when destroyed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an object which calls __construct and later __destruct.
- How many times: Exactly $n times, once per loop iteration.
Each new object adds a fixed amount of work for construction and destruction.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 constructions + 10 destructions) |
| 100 | About 200 (100 constructions + 100 destructions) |
| 1000 | About 2000 (1000 constructions + 1000 destructions) |
Pattern observation: The total work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time needed grows in a straight line as you create more objects.
[X] Wrong: "__construct and __destruct run only once no matter how many objects are created."
[OK] Correct: Each object calls these methods separately, so the work adds up with more objects.
Understanding how object creation and cleanup scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if __construct did a loop inside that runs m times? How would the time complexity change?"