Interface declaration and implementation in PHP - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
logmethod inside the loop. - How many times: The loop runs
ntimes, sologis calledntimes.
Each time we increase n, the number of log calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to log |
| 100 | 100 calls to log |
| 1000 | 1000 calls to log |
Pattern observation: The number of operations grows directly with n. Double n, double the calls.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times we call the method.
[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.
Understanding how interfaces affect time complexity helps you explain your design choices clearly and shows you know how code structure relates to performance.
"What if the log method itself contained a loop that runs m times? How would the time complexity change?"