Zend PHP 7 Certification – Functions – Anonymous Functions

This post covers the Anonymous Functions section of the Functions chapter when studying for the Zend PHP 7 Certification.

Anonymous functions, which are also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

<?php
$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { 
    return $val % 2 == 0; 
});
$arr_square = array_map(function($val) { 
    return $val * $val; 
}, $arr);

Anonymous functions can also be used as the values of variable.

<?php
$greet = function($name) {
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('World again!');

// Outputs:
Hello World 
Hello World again!

They may also inherit variables from the parent scope, therefore they must be passed to the function using the use language construct. As of PHP version 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

<?php
$message = 'Hello';

// Inherit $message
$example = function () use ($message) {
    echo $message;
};
$example();

// Outputs:
Hello

Attempting to change the variable in the parent scope will still result in the initial value of the variable being inherited in the function.

// Inherited variable's value is from when the function
// is defined, not when called.
$message = 'world';
$example();

// Outputs:
'Hello';

However, if you inherit a variable by reference, the changed value in the parent scope will be reflected in the function.

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
$example();

// The changed value in the parent scope
// is reflected inside the function call.
$message = 'world';
$example();

// Outputs:
Hello
world

View the other sections:

Note: This article is based on PHP version 7.1.