Closures and arrow functions
Anonymous functions
A closure is a function value without a name. Store it in a variable and call it like
a normal function. It keeps code local when a helper is needed only once.
Add parameter and return types exactly as you would for a named function.
$add = function (int $a, int $b): int {
return $a + $b;
};
echo $add(2, 3);
5
Capture with use
Closures do not see outer variables by default. List needed names in a
use clause to capture them by value at creation time.
Capture keeps the data flow explicit and avoids hidden dependence on globals.
$factor = 3;
$mul = function (int $x) use ($factor): int {
return $x * $factor;
};
echo $mul(10);
30
fn arrow functions
The short fn form fits one expression callbacks. It captures outer
variables automatically by value, so no use clause is needed.
Use it for mapping, filtering, and sorting where the logic fits on one line.
$factor = 3;
$mul = fn(int $x): int => $x * $factor;
$nums = [1, 2, 3];
var_dump(array_map($mul, $nums));
array(3) { [0]=> int(3) [1]=> int(6) [2]=> int(9) }
Pass callables around
Many core functions accept a callable to customize behavior. Pass a closure, an arrow function,
a function name as a string, or an array with an object and a method name.
Modern PHP also offers first-class callable syntax with three dots, which creates a closure
from any callable without writing a wrapper.
$words = ["pear", "apple", "fig"];
usort($words, fn(string $a, string $b): int => strlen($a) <=> strlen($b));
$fn = strlen(...);
echo $fn("hello");
5
Partial function application (PHP 8.6)
PHP 8.6 adds one more way to create a closure: call a
function and put a placeholder where an argument is still unknown. The
call does not run the function. It returns a closure that waits for the
missing arguments.
A ? leaves exactly one argument open, and
... leaves all the remaining ones open. The code
below needs PHP 8.6.
function greet(string $greeting, string $name): string
{
return "$greeting, $name!";
}
$hello = greet("Hello", ?);
var_dump(get_class($hello));
var_dump($hello("Anna"));
$toAnna = greet(?, "Anna");
var_dump($toAnna("Hi"));
$bye = greet("Bye", ...);
var_dump($bye("Bob"));
string(7) "Closure" string(12) "Hello, Anna!" string(9) "Hi, Anna!" string(9) "Bye, Bob!"
... can stand for several arguments at once. The closure takes all of them in the order of the function signature, and any arguments written before it stay fixed:
function order(
string $buyer,
string $item,
int $count,
float $price
): string {
$total = $count * $price;
return "$buyer: $count x $item = $total";
}
$forAnna = order("Anna", ...);
var_dump($forAnna("pen", 3, 1.5));
$bobBooks = order("Bob", "book", ...);
var_dump($bobBooks(2, 12.5));
string(19) "Anna: 3 x pen = 4.5" string(18) "Bob: 2 x book = 25"
Авторы статьи: Arthur Isaev, Андрей Олегович, Клавдия Кондакова