Open In App

What is Anonymous Function in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Anonymous functions are declared using the function keyword followed by the list of parameters and the function body.
  • They can capture variables from the surrounding scope using the use keyword.
  • Anonymous functions can be assigned to variables, passed as arguments to other functions, or returned from other functions.

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);


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads