Anonymous functions (closures) can be assigned to variables and passed around like values:
$double = function (int $n): int {
return $n * 2;
};
echo $double(5); // 10
By default, a closure does not have access to variables from its surrounding scope. Use use (...) to import them:
$taxRate = 0.08;
$addTax = function (float $price) use ($taxRate): float {
return $price * (1 + $taxRate);
};
Arrow functions (PHP 7.4+) are a concise shorthand that automatically capture outer variables by value, no use needed:
$addTax = fn (float $price) => $price * (1 + $taxRate);
Closures shine when working with built-in higher-order array functions:
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn ($n) => $n * 2, $numbers);
$evens = array_filter($numbers, fn ($n) => $n % 2 === 0);
$total = array_reduce($numbers, fn ($carry, $n) => $carry + $n, 0);
PHP 8.1+ also supports first-class callable syntax, letting you reference a named function or method as a closure without wrapping it manually: $mapper = strtoupper(...);.