Abstract classes and methods in PHP - Time & Space Complexity
We want to understand how the time it takes to run code with abstract classes and methods changes as the program grows.
Specifically, we ask: how does using abstract classes affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark\n";
}
}
$dogs = [];
for ($i = 0; $i < 5; $i++) {
$dogs[] = new Dog();
}
foreach ($dogs as $dog) {
$dog->makeSound();
}
This code defines an abstract class with an abstract method, then creates several objects from a subclass and calls the method on each.
- Primary operation: Looping through the array of Dog objects and calling
makeSound(). - How many times: The loop runs once for each Dog object, here 5 times.
As the number of Dog objects increases, the number of times makeSound() is called grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to makeSound() |
| 100 | 100 calls to makeSound() |
| 1000 | 1000 calls to makeSound() |
Pattern observation: The number of operations grows directly with the number of objects.
Time Complexity: O(n)
This means the time to run the method calls grows in a straight line as you add more objects.
[X] Wrong: "Using abstract classes makes the program slower because of extra overhead."
[OK] Correct: The abstract class itself does not add loops or repeated work; the time depends on how many objects and method calls you have, not on abstraction.
Understanding how abstract classes affect performance helps you explain design choices clearly and shows you know how code structure relates to speed.
"What if we added a nested loop inside makeSound() that runs n times? How would the time complexity change?"