The anonymous function in PHP lets you define a small task that doesn’t require a function name.
Table of Content
- Understand the Anonymous Function in PHP
- How to Pass Anonymous Functions as Arguments
- Return Anonymous Functions
- Instantly Invoked Function Expressions (IIFE)
- Add Anonymous Functions to Classes
- Understand the Closures in PHP
- Shorthand of Anonymous Function in PHP
- PHP Version Compatibility
- Examples of PHP Anonymous Functions and Closures
- Wrapping Up
- FAQs
Understand the Anonymous Function in PHP
You can use it like any other function, store it in a variable, or pass it as an argument. This feature was added in PHP 5.3.
You can declare an anonymous function with the function keyword and store it in a variable for later use.
Here is an example:
$greet = function($name) {
return "Hello, " . $name;
};
echo $greet("FlatCoding Students");This will show you the following output:
Hello, FlatCoding Students
You can assign the function to the following:
- A variable
- Store it in an array
- Pass it as an argument.
Anonymous functions can also capture variables from the parent scope with the use keyword.
For example:
$message = "Hello";
$greet = function() use ($message) {
echo $message;
};
$greet();You may need to use an anonymous function for the following reasons:
- Makes the code shorter
- Keeps small tasks in one place
- Works with functional style code
How to Pass Anonymous Functions as Arguments
You can pass the anonymous function as an argument for built-in functions in PHP.
For example:
$numbers = [1, 2, 3, 4];
$doubled = array_map(function($n) {
return $n * 2;
}, $numbers);
print_r($doubled);The output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
Here is another example with usort:
$names = ["John", "Alex", "Zoe"];
usort($names, function($a, $b) {
return strlen($a) - strlen($b);
});
print_r($names);Output:
Array
(
[0] => Zoe
[1] => John
[2] => Alex
)
Return Anonymous Functions
PHP allows you to write a function that creates and returns another function. You can use this pattern to make factories or change logic.
Here is an example:
function multiplier($factor) {
return function($number) use ($factor) {
return $number * $factor;
};
}
$double = multiplier(2);
echo $double(5); // 10It sets a function that returns an anonymous function. The inner function takes a value from the outer function to multiply its input.
Here is another example:
function greeter($param) {
return function($name) use ($param) {
return $param. ', ' . $name;
};
}
$sayHello = greeter('Hello');
echo $sayHello('Bob');The output:
Hello, Bob
This function returns another function that takes a parameter from the first function, and the inner one adds that parameter to a name.
Instantly Invoked Function Expressions (IIFE)
An IIFE runs right after you create it. PHP uses wrapping parentheses to make this work
Here is an example:
$result = (function() {
return 5 * 5;
})();
echo $result; // 25This runs an anonymous function immediately without inputs. It calculates five squared inside the function.
For another example:
$message = (function($name) {
return "Welcome, " . $name;
})("Charlie");
echo $message;The output:
Welcome, Charlie
This defines and runs an anonymous function directly. It takes a name as input and builds a welcome message.
Add Anonymous Functions to Classes
You can store anonymous functions as properties in classes. Here is an example:
class Logger {
public $log;
public function __construct() {
$this->log = function($msg) {
echo "[LOG]: " . $msg;
};
}
}
$logger = new Logger();
$logger->log->__invoke("System started");The output:
[LOG]: System started
This class assigns an anonymous function to a property in its constructor. The function prints a log message with a prefix. It shows how to call the function with the property’s __invoke method.
Here is another example:
class Calculator {
public $operation;
}
$calc = new Calculator();
$calc->operation = function($a, $b) {
return $a + $b;
};
echo $calc->operation->__invoke(3, 4); // 7This class has a public property holding an anonymous function that adds two numbers. You run the function by calling __invoke with two arguments.
Understand the Closures in PHP
A closure is an anonymous function implemented with the closure mechanism that captures variables from its parent scope. It keeps these variables even when the outer function exits.
So, PHP generates an instance of the closure class to represent it when you create a closure. You use the use keyword to import external variables.
Here is an example:
$message = "Hi";
$closure = function($name) use ($message) {
return $message . ", " . $name;
};
echo $closure("Dana");The output:
Hi, Dana
It keeps $message from the outer scope.
Here is another example:
function counter() {
$count = 0;
return function() use (&$count) {
$count++;
return $count;
};
}
$increment = counter();
echo $increment(); // 1
echo $increment(); // 2This remembers and updates $count between calls.
Shorthand of Anonymous Function in PHP
PHP supports a short syntax for anonymous functions called arrow functions.
Here is the syntax:
$add = fn($a, $b) => $a + $b;
echo $add(5, 3); // 8Here are the differences between anonymous functions and arrow functions:
Anonymous functions use the use keyword for external variables, while the arrow functions automatically capture them.
The arrow functions inherit the parent scope by default. Anonymous functions need to use import variables.
Here is a table that shows you the key differences:
| Feature | Anonymous Function | Arrow Function |
|---|---|---|
| Scope Binding | Manual with use | Automatic parent scope |
| Syntax | function(...) use (...) { ... } | fn(...) => ... |
| Introduced In | PHP 5.3 | PHP 7.4 |
PHP Version Compatibility
- Anonymous functions appeared in PHP 5.3.
- Closures with
usealso appeared in PHP 5.3. - Closure::fromCallable was added in PHP 7.1.
- Typed properties and return types appeared in PHP 7.4 and 7.1.
Examples of PHP Anonymous Functions and Closures
Assign an anonymous function to a variable in PHP:
$square = function($n) {
return $n * $n;
};
echo $square(6); // 36This function stores in a variable for later use and takes a number and multiplies it by itself.
Append an exclamation mark in PHP:
$appendExclamation = function($text) {
return $text . "!";
};
echo $appendExclamation("Wow"); // Wow!It takes one text input and adds an exclamation mark to the end of the text. It shows a quick way to change text with a function.
Repeat a text in a PHP anonymous function:
$repeat = function($text, $times) {
return str_repeat($text, $times);
};
echo $repeat("Ho ", 3);The output:
Ho Ho Ho
This code defines an anonymous function with two inputs. It repeats the text the given number of times. It shows how to use str_repeat inside an assigned function.
Remove the last character of a string using an anonymous function:
$removeLastChar = function($text) {
return substr($text, 0, -1);
};
echo $removeLastChar("Hello!"); This function takes a string that uses substr to split the last character, and returns the shortened string.
Here is the output:
Hello
Chains multiple checks:
$validators = [
function($v) { return is_numeric($v); },
function($v) { return $v > 0; }
];
$value = 10;
$valid = array_reduce($validators, function($carry, $fn) use ($value) {
return $carry && $fn($value);
}, true);
echo $valid ? "Valid" : "Invalid"; // ValidThis code creates two anonymous functions in an array. It checks if a value is numeric and greater than zero. It uses array_reduce to apply all checks and decide if the value passes validation.
Wrapping Up
You learned what anonymous functions are and how to use them in PHP.
Here is a quick recap:
- PHP supports these features since version 5.3 for anonymous functions and version 7.4 for arrow functions.
- PHP uses the
Closureclass behind every anonymous function, and many of these functions encapsulate logic dynamically. - Anonymous functions let you define functions without names.
- Closures import variables from the outer scope.
- Arrow functions simplify how scope links to variables.
FAQs
What is an anonymous function?
$greet = function($name) { return "Hello, " . $name; };
echo $greet("World");
How do you declare and use an anonymous function in PHP?
function keyword and assign it to a variable.
Example:
$sum = function($a, $b) { return $a + $b; };
echo $sum(5, 3);
You can also pass it as a callback in array functions.What is the difference between anonymous functions and arrow functions in PHP?
fn keyword and automatically capture variables from the parent scope.
They are limited to a single expression. Example:
$factor = 2;
$multiply = fn($x) => $x * $factor;
echo $multiply(5); What are common use cases for anonymous functions?
- Callbacks in
array_map,usort, and events - Creating isolated scope with IIFEs
- Small inline logic without naming clutter
$numbers = [1, 2, 3, 4];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even);
Similar Reads
let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…
You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…
Inserting documents into your MongoDB collections is one of the most basic but important tasks when working with PHP. In…
PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…
Array values may look the same, but keys can differ. The array_diff_assoc in PHP finds differences by both values and…
The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…
The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…
PHP 5 added support for classes and interfaces. This made object-oriented code possible with one feature being polymorphism. That means…
The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…
Constants in PHP store fixed values that don’t change during execution. We will cover the following topics in this article:…