Reading — step 1 of 5
Learn
~1 min readFunctions
PHP has two anonymous-function styles. Standard closures:
$double = function ($n) {
return $n * 2;
};
echo $double(5); // 10
Closures don't see outer scope variables by default — you have to opt in with use:
$factor = 3;
$multiply = function ($n) use ($factor) {
return $n * $factor;
};
Arrow functions (PHP 7.4+) are shorter and capture outer variables automatically:
$factor = 3;
$multiply = fn($n) => $n * $factor; // implicit return, auto-capture
Limitations: arrow functions are single-expression only and capture by value (not reference).
Closures are first-class — pass them to array_map, array_filter, array_reduce, usort, etc.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…