0
0
PHPprogramming~5 mins

__construct and __destruct in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: __construct and __destruct
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new object adds a fixed amount of work for construction and destruction.

Input Size (n)Approx. Operations
10About 20 (10 constructions + 10 destructions)
100About 200 (100 constructions + 100 destructions)
1000About 2000 (1000 constructions + 1000 destructions)

Pattern observation: The total work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line as you create more objects.

Common Mistake

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

Interview Connect

Understanding how object creation and cleanup scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if __construct did a loop inside that runs m times? How would the time complexity change?"