__invoke for callable objects in PHP - Time & Space Complexity
Let's see how calling an object like a function affects the time it takes to run the code.
We want to know how the number of calls changes the work done.
Analyze the time complexity of the following code snippet.
class Multiplier {
private int $factor;
public function __construct(int $factor) {
$this->factor = $factor;
}
public function __invoke(int $number): int {
return $number * $this->factor;
}
}
$multiplier = new Multiplier(5);
for ($i = 0; $i < 100; $i++) {
echo $multiplier($i) . "\n";
}
This code creates an object that multiplies numbers and calls it like a function 100 times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
__invokemethod on the object. - How many times: 100 times, once for each loop iteration.
Each time we increase the number of calls, the work grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to __invoke |
| 100 | 100 calls to __invoke |
| 1000 | 1000 calls to __invoke |
Pattern observation: The number of operations grows directly with the number of calls.
Time Complexity: O(n)
This means if you double the number of calls, the total work roughly doubles too.
[X] Wrong: "Calling an object with __invoke is slower and adds extra hidden loops."
[OK] Correct: The __invoke method runs just like a normal function call, so it doesn't add extra loops or slow down the code beyond the calls you make.
Understanding how callable objects work and their time cost helps you explain your code clearly and shows you know how PHP handles function-like objects efficiently.
"What if the __invoke method itself contained a loop over an array of size n? How would the time complexity change?"