Skip to content

Anonymous Functions

Anonymous functions are functions without a name.
They are often used for short tasks, callbacks, or when passing functions as arguments.

Anonymous functions are also called closures.

$greet = function () {
echo "Hello World";
};
$greet();
$add = function ($a, $b) {
return $a + $b;
};
echo $add(5, 3);

The use keyword allows access to variables from the parent scope.

$message = "Hello";
$printMessage = function () use ($message) {
echo $message;
};
$printMessage();