0
0
PHPprogramming~5 mins

Abstract classes and methods in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes and methods
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the number of Dog objects increases, the number of times makeSound() is called grows the same way.

Input Size (n)Approx. Operations
1010 calls to makeSound()
100100 calls to makeSound()
10001000 calls to makeSound()

Pattern observation: The number of operations grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how abstract classes affect performance helps you explain design choices clearly and shows you know how code structure relates to speed.

Self-Check

"What if we added a nested loop inside makeSound() that runs n times? How would the time complexity change?"