PHP Anonymous Functions (Closures)
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most often used as the value of callback parameters, but they have many other uses.
1. Basic Syntax
Anonymous functions are implemented using the Closure class.
$greet = function($name) {
echo "Hello " . $name;
};
$greet('World');
$greet('PHP');
2. Inheriting Variables from Parent Scope
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
$message = 'hello';
// Inherit $message
$example = function () use ($message) {
echo $message;
};
$example(); // Outputs: hello
3. Example: Callbacks
Anonymous functions are frequently used as callbacks for built-in array functions.
$numbers = [1, 2, 3, 4];
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squared);
// Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )