0
0
PHPprogramming~5 mins

Extending classes in PHP - Time & Space Complexity

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

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop that goes through each item in the array.
  • How many times: Once for each item in the input array.
How Execution Grows With Input

As the number of items grows, the loop runs more times, printing each item once.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items processed.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the child class added another loop over the items? How would the time complexity change?"