0
0
PHPprogramming~5 mins

Constructor inheritance in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor inheritance
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when using constructor inheritance 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 ParentClass {
    public function __construct() {
        // Some setup work
        for ($i = 0; $i < 100; $i++) {
            // Simulate work
        }
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct();
        // Additional setup
    }
}

$objects = [];
for ($j = 0; $j < $n; $j++) {
    $objects[] = new ChildClass();
}
    

This code creates many objects of a child class that calls the parent constructor each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating $n objects, each running a loop of 100 steps in the parent constructor.
  • How many times: The outer loop runs $n times, and inside each, the parent constructor runs a fixed 100-step loop.
How Execution Grows With Input

Each new object adds the same fixed amount of work from the parent constructor.

Input Size (n)Approx. Operations
1010 x 100 = 1,000
100100 x 100 = 10,000
10001000 x 100 = 100,000

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Calling the parent constructor inside the child constructor makes the time grow faster than the number of objects."

[OK] Correct: The parent constructor work is fixed and does not depend on n, so it just adds a constant amount of work per object.

Interview Connect

Understanding how constructors run when inherited helps you explain object creation costs clearly in interviews.

Self-Check

"What if the parent constructor had a loop that depends on n instead of a fixed 100? How would the time complexity change?"