Multiple interface implementation in PHP - Time & Space Complexity
When a class implements multiple interfaces, it must provide all the methods those interfaces require.
We want to understand how this affects the time it takes to run the program.
Analyze the time complexity of the following code snippet.
interface A {
public function methodA();
}
interface B {
public function methodB();
}
class MyClass implements A, B {
public function methodA() {
// simple operation
}
public function methodB() {
// simple operation
}
}
$obj = new MyClass();
$obj->methodA();
$obj->methodB();
This code shows a class implementing two interfaces and calling their methods.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling methods defined by interfaces.
- How many times: Each method is called once here, no loops or recursion.
Since there are no loops or repeated calls, the time grows very little as input size grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 method calls |
| 100 | 2 method calls |
| 1000 | 2 method calls |
Pattern observation: The number of operations stays the same regardless of input size.
Time Complexity: O(1)
This means the time to run does not grow with input size; it stays constant.
[X] Wrong: "Implementing more interfaces makes the program slower as input grows."
[OK] Correct: The number of interfaces does not affect how many times methods run unless loops or recursion are involved.
Understanding how interface implementation affects performance helps you explain design choices clearly and confidently.
"What if each method called inside the class had a loop over an input array? How would the time complexity change?"