0
0
PHPprogramming~5 mins

__invoke for callable objects in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: __invoke for callable objects
O(n)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the __invoke method on the object.
  • How many times: 100 times, once for each loop iteration.
How Execution Grows With Input

Each time we increase the number of calls, the work grows in the same way.

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

Pattern observation: The number of operations grows directly with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of calls, the total work roughly doubles too.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the __invoke method itself contained a loop over an array of size n? How would the time complexity change?"