Advertisement
Beginner PHP, Closures & Anonymous Functions

What is an anonymous function in PHP, and how does it differ from a regular named function?

Short answer

An anonymous function, also called a closure, is a function without a name that can be assigned to a variable, passed as an argument to another function, or returned from a function, which is especially useful for short pieces of logic used only in one specific place, unlike a…

Save PHP mock interview
Advertisement
AModel answer
An anonymous function, also called a closure, is a function without a name that can be assigned to a variable, passed as an argument to another function, or returned from a function, which is especially useful for short pieces of logic used only in one specific place, unlike a regular named function which is defined once and referenced by that name everywhere it is needed throughout your code.
$greet = function ($name) {
    return "Hello, $name!";
};
echo $greet('Ali');
Real-world example
A form validation system uses a short anonymous function to define a one off custom validation rule for a specific field, avoiding the need to create and name a separate standalone function that would only ever be used in that single spot.
Likely follow-ups
  • When should you use a named function instead of an anonymous function?
  • Can an anonymous function be assigned to a class property?
Related topics