Anonymous function
suggest changeAn anonymous function is just a function that doesn’t have a name.
// Anonymous function
function() {
return "Hello World!";
};
In PHP, an anonymous function is an expression. When it is used as a statement, it must end with a semicolon (;).
An anonymous function can be assigned to a variable.
// Anonymous function assigned to a variable
$sayHello = function($name) {
return "Hello $name!";
};
print $sayHello('John'); // Hello John
Or it can be passed as a parameter to another function.
$users = [
['name' => 'Alice', 'age' => 20],
['name' => 'Bobby', 'age' => 22],
['name' => 'Carol', 'age' => 17]
];
// Map function applying anonymous function
$userName = array_map(function($user) {
return $user['name'];
}, $users);
print_r($userName); // Array ( [0] => Alice [1] => Bobby [2] => Carol )
Or it can be returned from another function.
Self-executing anonymous functions:
// For PHP 7.x
(function () {
echo "Hello world!";
})();
// For PHP 5.x
call_user_func(function () {
echo "Hello world!";
});
Passing an argument into self-executing anonymous functions:
// For PHP 7.x
(function ($name) {
echo "Hello $name!";
})('John');
// For PHP 5.x
call_user_func(function ($name) {
echo "Hello $name!";
}, 'John');
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents