0
0
PHPprogramming~5 mins

Interface declaration and implementation in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interface declaration and implementation
O(n)
Understanding Time Complexity

When using interfaces in PHP, it's important to know how the program's running time changes as the code works with different objects.

We want to see how the time cost grows when calling methods defined by an interface.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface Logger {
    public function log(string $message): void;
}

class FileLogger implements Logger {
    public function log(string $message): void {
        // Simulate writing to a file
        file_put_contents('log.txt', $message . PHP_EOL, FILE_APPEND);
    }
}

$logger = new FileLogger();
for ($i = 0; $i < $n; $i++) {
    $logger->log("Message $i");
}
    

This code defines an interface and a class that implements it. Then it calls the log method inside a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the log method inside the loop.
  • How many times: The loop runs n times, so log is called n times.
How Execution Grows With Input

Each time we increase n, the number of log calls grows the same way.

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

Pattern observation: The number of operations grows directly with n. Double n, double the calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of times we call the method.

Common Mistake

[X] Wrong: "Using an interface makes the code slower in a way that changes the time complexity."

[OK] Correct: Calling methods through an interface adds a tiny fixed cost, but it does not change how the total time grows with input size.

Interview Connect

Understanding how interfaces affect time complexity helps you explain your design choices clearly and shows you know how code structure relates to performance.

Self-Check

"What if the log method itself contained a loop that runs m times? How would the time complexity change?"