PHP Functional Programming Anonymous function

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

An anonymous function is just a function that doesn't have a name.

// Anonymous function
function() {
    return "Hello World!";
};

In PHP, an anonymous function is treated like an expression and for this reason, it should be ended with a semicolon ;.

An anonymous function should be assigned to a variable.

// Anonymous function assigned to a variable
$sayHello = function($name) {
    return "Hello $name!";
};

print $sayHello('John'); // Hello John

Or it should be passed as parameter of 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($usersName); // ['Alice', 'Bobby', 'Carol']

Or even been 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');


Got any PHP Question?