Usage
- Inline Definition: Anonymous functions can be defined directly within the code, eliminating the need for named function declarations.
- Flexibility: They can be used as callbacks or event handlers where a small, reusable function is required.
- Closure Scope: Anonymous functions can access variables from the enclosing scope using the
use
keyword, allowing for the encapsulation of data.
Example:
// Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);
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.