Closures are anonymous functions stored in variables and passed around. Use the use keyword to capture outer scope variables by value. They are used for callbacks, event handlers, middleware pipelines, and lazy evaluation.
Closures (Anonymous Functions)
// Closure as callback
$greet = function(string $name): string {
return "Hello, $name!";
};
echo $greet("Alice"); // Hello, Alice!
// Passing closures to functions
$numbers = [3, 1, 4, 1, 5, 9];
usort($numbers, fn($a, $b) => $a - $b);
// Returning a closure
function multiplier(int $factor): Closure {
return fn(int $n) => $n * $factor;
}
$double = multiplier(2);
$triple = multiplier(3);
echo $double(5); // 10
echo $triple(5); // 15
// Binding closures to objects
class Counter {
private int $count = 0;
}
$increment = Closure::bind(
fn() => $this->count++,
new Counter(),
Counter::class
);