Constructor inheritance in PHP - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Creating
$nobjects, each running a loop of 100 steps in the parent constructor. - How many times: The outer loop runs
$ntimes, and inside each, the parent constructor runs a fixed 100-step loop.
Each new object adds the same fixed amount of work from the parent constructor.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 x 100 = 1,000 |
| 100 | 100 x 100 = 10,000 |
| 1000 | 1000 x 100 = 100,000 |
Pattern observation: The total work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to run grows in a straight line as you create more objects.
[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.
Understanding how constructors run when inherited helps you explain object creation costs clearly in interviews.
"What if the parent constructor had a loop that depends on n instead of a fixed 100? How would the time complexity change?"