PHP Closures, Arrow Functions, and use()
Lesson 9 of 43 in the PHP 8 learning path.
How do I pass a small function to array_map or array_filter?
A closure is a function value you can pass into array_filter() or array_map(). An arrow function, written with fn, is a short closure for a single expression. It captures variables from the surrounding scope by value automatically, so the $passing threshold used inside fn (int $score): bool => $score >= $passing is the 75 that was current when the arrow was created. Changing $passing to 100 afterward does not move the threshold the arrow already captured.
A classic closure does not capture outer variables unless you list them in use (). The sample builds a labeler with use ($prefix) while $prefix is Score, then changes the outer variable to Changed. The labels still say Score, because use () copied the string. use (&$prefix) would share the variable instead, and later edits would leak into labels that were supposed to stay stable. Arrow functions cannot contain multiple statements.
Syntax & Parameters
fn (int $score): bool => $score >= $passing
function (int $score) use ($prefix): string
Example
<?php
declare(strict_types=1);
$scores = [68, 75, 91, 54, 88];
$passing = 75;
$keep = fn (int $score): bool => $score >= $passing;
$passing = 100;
$passed = array_values(array_filter($scores, $keep));
$prefix = 'Score';
$label = function (int $score) use ($prefix): string {
return $prefix . ' ' . $score;
};
$prefix = 'Changed';
$labels = array_map($label, $passed);
echo 'passed=' . implode(',', $passed) . "\n";
echo 'labels=' . implode('|', $labels) . "\n";
echo 'prefix_after=' . $prefix . "\n";
echo 'count=' . count($labels) . "\n";
$named = array_map(
static function (int $score): string {
return 'pt:' . $score;
},
$passed
);
echo 'named=' . implode(',', $named) . "\n";
Expected Output
passed=75,91,88 labels=Score 75|Score 91|Score 88 prefix_after=Changed count=3 named=pt:75,pt:91,pt:88
Line-by-Line Walkthrough
- declare(strict_types=1) is on for this file. array_filter() and array_map() still call these callbacks from internal code.
- $scores holds five quiz results and $passing starts at 75, the grade-book threshold.
- The arrow fn captures $passing by value at the moment it is created, and the body is the single comparison $score >= $passing.
- $passing is then set to 100. The arrow keeps 75, so 75, 91, and 88 still pass.
- array_values() reindexes the filtered list because array_filter() preserves the original keys.
- The closure lists use ($prefix) while $prefix is Score, which copies that string into the closure.
- Assigning Changed to the outer $prefix leaves the captured copy alone.
- array_map() runs the closure over the passing scores and builds Score 75, Score 91, and Score 88.
- prefix_after prints Changed, which shows the outer variable moved and the labels did not.
- The static closure in the last array_map() captures nothing and prefixes each passing score with pt:.
Common Pitfalls & Security
Capturing the wrong variable, or capturing it by reference, makes a roster label depend on later loop assignments. Arrow functions hide the capture list, which is convenient and also easy to miss during review. Callbacks passed to array_map() are invoked by internal code, so a strict_types file does not make those callback calls strict.
- use ($prefix) copies the current value. use (&$prefix) aliases the outer variable, and a later assignment shows up inside labels that already looked finished.
- An arrow function captures by value only. It cannot use a by-reference capture, and it cannot hold two statements. A multi-step label belongs in a closure or a named function.
- array_filter() keeps keys. Imploding the raw result is usually fine, and json_encode() of that result can become a JSON object instead of a list. array_values() restores a list.
- A closure that reads $_POST directly couples a pure filter to the current request. Pass the threshold in as $passing so the filter can be tested with a fixed list.
- Unsafe anti-pattern (do not ship): building option labels with raw student text inside the closure and printing them without htmlspecialchars. The closure does not escape HTML.
- Internal callback calls coerce. array_map() can pass a numeric string into an int parameter without a TypeError even in this strict file. Normalize the list first when that matters.
Best Practices & Modern Standards
Use an arrow function on PHP 8.3 when the callback is one expression and capturing outer values by copy is what you want. Use a closure with an explicit use () list when you want the captured names to be obvious in review. Use a named function when the grade threshold or the label format is part of school policy that unit tests should call directly.
Mark a closure static when it does not need $this. The final array_map() in the sample is static for that reason. Reindex with array_values() after array_filter() before you encode a list as JSON or pass it to a typed list consumer.
Real-World Use
The grade book filters a section to students at or above 75, then labels the passing scores for a progress email. The arrow keeps the threshold from the moment the teacher applied the filter, even if the screen later edits the cutoff. The closure stamps the word Score onto each remaining value, and a later change to the prefix variable does not rewrite labels that were already built.
Frequently Asked Questions
Do arrow functions capture variables automatically?
Yes, by value. The sample creates the arrow while $passing is 75, then sets $passing to 100. The filter still uses 75. There is no use () clause on an arrow function.
When do I write use ()?
On a traditional closure, outer variables are not visible unless you name them in use (). The sample captures $prefix that way. Leave the variable out of use () and the closure cannot read it.
Does use ($prefix) see later changes?
No. It copies the value at creation. The sample changes the outer prefix to Changed and the labels still start with Score. use (&$prefix) would share the variable, which is rarely what a label wants.
Why call array_values() after array_filter()?
array_filter() keeps the original keys, so a filtered list of scores can have keys 1, 2, and 4. array_values() builds keys 0, 1, and 2 so the result encodes as a JSON list.