0
0
PHPprogramming~5 mins

Closures and variable binding with use in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures and variable binding with use
O(n)
Understanding Time Complexity

We want to understand how the time needed to run a closure with variable binding changes as the input grows.

How does the number of operations grow when using closures with variables passed by use?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$numbers = [1, 2, 3, 4, 5];
$sum = 0;

$addToSum = function($num) use (&$sum) {
    $sum += $num;
};

foreach ($numbers as $number) {
    $addToSum($number);
}

echo $sum;
    

This code sums all numbers in an array using a closure that accesses a variable by reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop that calls the closure for each number.
  • How many times: Once for each element in the $numbers array.
How Execution Grows With Input

Each number in the array causes one call to the closure, which adds it to the sum.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items in the array.

Common Mistake

[X] Wrong: "Using use inside closures makes the code slower or adds hidden loops."

[OK] Correct: The use keyword just binds variables; it does not add extra loops or slow down the code beyond the existing operations.

Interview Connect

Understanding how closures work with variable binding helps you write clear and efficient code, a skill valued in many coding challenges and real projects.

Self-Check

"What if the closure was called inside a nested loop over the array? How would the time complexity change?"