Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Anonymous functions and closures

A function can be put into a variable, passed to another function or returned from one. Such functions have no name and are called anonymous. You have already met them in array_map() and usort().

A function in a variable

An anonymous function is declared without a name and ends with a semicolon:

<?php
 
$double = function ($number) {
    return $number * 2;
};
 
echo $double(5); // 10

It is called through the variable — with the same $ sign.

A function as an argument

The main use is passing behavior into another function:

<?php
 
$words = ['php', 'html', 'css'];
 
$upper = array_map(function ($word) {
    return strtoupper($word);
}, $words);
 
echo implode(', ', $upper); // PHP, HTML, CSS

Closures and use

A regular anonymous function does not see outside variables. The ones it needs are listed in use — the function "captures" their values:

<?php
 
$tax = 0.2;
 
$withTax = function ($price) use ($tax) {
    return $price * (1 + $tax);
};
 
echo $withTax(100); // 120

A function with captured variables is called a closure. The value is copied at the moment of creation: if $tax changes later, the function will not notice.

Arrow functions

The short fn form suits functions made of a single expression. It sees outside variables by itself, no use needed:

<?php
 
$tax = 0.2;
 
$withTax = fn ($price) => $price * (1 + $tax);
 
echo $withTax(100); // 120

The word return is not written: the result of the expression is returned automatically.

A function that returns a function

This is how a family of similar functions is created without repeating code:

<?php
 
function multiplier($factor)
{
    return fn ($number) => $number * $factor;
}
 
$double = multiplier(2);
$triple = multiplier(3);
 
echo $double(10), ' ', $triple(10); // 20 30

Each returned function remembers its own value of $factor.

The callable type

A parameter that expects a function is marked with the callable type:

<?php
 
function applyTwice(callable $action, $value)
{
    return $action($action($value));
}
 
echo applyTwice(fn ($n) => $n + 3, 10), "\n"; // 16
echo applyTwice('strrev', 'abc');             // abc

The name of a built-in function can be passed as a string.

Common mistake

An arrow function gets copies of outside variables and cannot change them. To change a variable outside, you need a regular anonymous function and the & sign in use:

<?php
 
$count = 0;
 
$increment = function () use (&$count) {
    $count++;
};
 
$increment();
$increment();
 
echo $count; // 2

Thanks for reading!

Donate to the site — we work hard for you.