Closures and variable binding with use in PHP - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
foreachloop that calls the closure for each number. - How many times: Once for each element in the
$numbersarray.
Each number in the array causes one call to the closure, which adds it to the sum.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the number of elements.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the array.
[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.
Understanding how closures work with variable binding helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if the closure was called inside a nested loop over the array? How would the time complexity change?"