Extending classes in PHP - Time & Space Complexity
When we extend classes in PHP, we add new features to existing code. It's important to see how this affects the time it takes for the program to run.
We want to know: how does adding a child class change the work the program does?
Analyze the time complexity of the following code snippet.
class ParentClass {
public function process(array $items) {
foreach ($items as $item) {
echo $item . "\n";
}
}
}
class ChildClass extends ParentClass {
public function process(array $items) {
parent::process($items);
echo "Done processing " . count($items) . " items.";
}
}
$child = new ChildClass();
$child->process([1, 2, 3, 4, 5]);
This code defines a parent class with a method that prints each item in an array. The child class extends it by calling the parent method and then printing a summary message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
foreachloop that goes through each item in the array. - How many times: Once for each item in the input array.
As the number of items grows, the loop runs more times, printing each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items processed.
[X] Wrong: "Extending a class always makes the program slower by a lot."
[OK] Correct: Extending a class just adds a little extra work, like printing a summary. The main loop still runs once per item, so the overall time grows the same way.
Understanding how extending classes affects time helps you write clear and efficient code. It shows you can think about both design and performance, a skill many developers value.
"What if the child class added another loop over the items? How would the time complexity change?"