Why closures matter in PHP - Performance Analysis
We want to see how using closures in PHP affects how long a program takes to run.
Specifically, we ask: how does the program's work grow when closures are involved?
Analyze the time complexity of the following code snippet.
$numbers = range(1, $n);
$results = [];
$filterEven = function($num) {
return $num % 2 === 0;
};
foreach ($numbers as $number) {
if ($filterEven($number)) {
$results[] = $number;
}
}
This code creates a list of numbers, defines a closure to check even numbers, and uses it to filter the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Exactly once for each number, so n times.
- Closure call: The closure runs once per number inside the loop.
As the list gets bigger, the program checks each number once using the closure.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Using a closure makes the code slower by a lot because it adds extra steps."
[OK] Correct: The closure is just a small function called inside the loop, so it adds a tiny fixed cost per item, not a big change in growth.
Understanding how closures affect time helps you explain your code choices clearly and shows you think about efficiency in real projects.
"What if the closure itself contained a loop over the entire list? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of closure and compare options
A closure is an anonymous function that can remember and use variables from the scope where it was created. Only An anonymous function that can access variables from its parent scope describes an anonymous function with access to outer variables, which matches the closure concept.Final Answer:
An anonymous function that can access variables from its parent scope -> Option BQuick Check:
Closure = Anonymous function with outer scope access [OK]
- Confusing closures with regular named functions
- Thinking closures cannot access outside variables
- Mixing closures with class methods
Solution
Step 1: Recall PHP closure syntax and check options
Closures are created using the keywordfunctionwithout a name, assigned to a variable. $func = function() { echo 'Hello'; }; usesfunction() { ... }assigned to$func, which is correct syntax.Final Answer:
$func = function() { echo 'Hello'; }; -> Option CQuick Check:
Closure syntax = function() { ... } [OK]
- Using 'closure()' keyword which does not exist
- Trying to name the anonymous function
- Using 'new function()' which is invalid
$message = 'Hi';
$greet = function() use ($message) {
echo $message;
};
$greet();
Solution
Step 1: Understand the use keyword and trace execution
The closure usesuse ($message)to import the variable$messagefrom the outer scope. When$greet()is called, it echoes the value of$message, which is 'Hi'.Final Answer:
Hi -> Option DQuick Check:
Closure with use outputs outer variable value [OK]
- Forgetting to use 'use' keyword to import variables
- Expecting closure to access outer variables automatically
- Confusing output with repeated prints
$count = 0;
$increment = function() {
$count++;
};
$increment();
echo $count;
Solution
Step 1: Analyze variable access and PHP scope rules in closures
The closure tries to increment$countbut does not import it withuse, so$countis undefined inside. Variables outside closures must be imported withuseto be accessible inside closures.Final Answer:
Closure cannot access $count without 'use' keyword -> Option AQuick Check:
Use 'use' to access outer variables inside closures [OK]
- Assuming closures access outer variables automatically
- Thinking increment inside closure changes outer variable without 'use'
- Confusing syntax errors with scope errors
Solution
Step 1: Understand private data and how closures enable it
Private data means variables that cannot be accessed directly from outside code. Closures can enclose variables in their scope, so only the closure can access or modify them, hiding them from outside.Final Answer:
Closures can capture variables in their scope, hiding them from outside access -> Option AQuick Check:
Closures enable private data by capturing variables [OK]
- Thinking closures make variables global
- Confusing closures with constants
- Believing closures block all variable access
Ready to prove it?
Pass the test and this pattern moves unknown
