Anonymous function

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Functional programming:
* Anonymous function
* Scope

Table Of Contents
2 Arrays
3 Functional programming
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR