Open In App

What is Anonymous Function in PHP ?

Anonymous Function, also known as closures, are functions in PHP that do not have a specific name and can be defined inline wherever they are needed. They are useful for situations where a small, one-time function is required, such as callbacks for array functions, event handling, or arguments to other functions.

Syntax:

$anonymousFunction = function($arg1, $arg2, ...) {
// Function body
};

Important Points

Usage

Example:

// Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);

Article Tags :