TExcelTAD
Home › PHP › PHP First-class Callables & Arrow Functions

PHP First-class Callables & Arrow Functions

In PHP, functions are values. You can store a function in a variable, pass it to another function, return it, and call it later. Anything that can be called this way is a callable. This lesson covers the different ways to create callables: anonymous functions (closures), arrow functions, the modern first-class callable syntax, and the older string/array forms you'll still see in existing code.

Anonymous functions (closures)

An anonymous function has no name; you assign it to a variable or pass it directly. Under the hood it is an object of class Closure.

php · try it yourself
<?php
$greet = function (string $name): string {
    return "Hi, $name!";
};

echo $greet("Linh"), "\n";
echo get_class($greet), "\n";

$names = ["ada", "grace", "linus"];
$capitalised = array_map(function ($n) {
    return ucfirst($n);
}, $names);

echo implode(", ", $capitalised), "\n";
Hi, Linh!
Closure
Ada, Grace, Linus

Capturing variables with use

A normal anonymous function cannot see variables from the surrounding scope. You must import them explicitly with use. By default the value is copied at the moment the closure is created; add & to capture by reference.

php · try it yourself
<?php
$rate = 0.2;

$addTax = function (float $price) use ($rate): float {
    return round($price * (1 + $rate), 2);
};

$rate = 0.5; // too late: the closure already copied 0.2
echo $addTax(100), "\n";

$count = 0;
$increment = function () use (&$count): void {
    $count++;
};
$increment();
$increment();
echo "count = $count\n";
120
count = 2

Arrow functions

Arrow functions (fn) are a short syntax for closures whose body is a single expression. They capture outer variables automatically (by value), so no use is needed.

php · try it yourself
<?php
$discount = 10;
$prices = [20, 45, 80];

$after = array_map(fn($p) => $p - $p * $discount / 100, $prices);
echo implode(" ", $after), "\n";

$expensive = array_filter($prices, fn(int $p): bool => $p > 30);
echo implode(" ", $expensive), "\n";

$multiplier = fn($x) => fn($y) => $x * $y;   // nesting works too
$triple = $multiplier(3);
echo $triple(7), "\n";
18 40.5 72
45 80
21
function () use (...) { } fn() => expr
Body Any number of statements Exactly one expression
Outer variables Only those listed in use All, captured automatically by value
By reference capture use (&$x) Not possible
return keyword Needed Implicit

First-class callable syntax: name(...)

PHP 8.1 added a clean way to turn any existing function or method into a Closure: write the call with literally three dots (...) as the argument list.

php · try it yourself
<?php
class Formatter
{
    public function __construct(private string $prefix) {}

    public function format(string $s): string
    {
        return $this->prefix . $s;
    }

    public static function upper(string $s): string
    {
        return strtoupper($s);
    }
}

$len = strlen(...);
echo $len("callable"), "\n";

$f = new Formatter("> ");
$fmt = $f->format(...);
$up = Formatter::upper(...);

$words = ["alpha", "beta"];
print_r(array_map($fmt, $words));
print_r(array_map($up, $words));

var_dump($len instanceof Closure);
8
Array
(
    [0] => > alpha
    [1] => > beta
)
Array
(
    [0] => ALPHA
    [1] => BETA
)
bool(true)

The (...) form is checked by PHP right away (a typo in the name is an error on that line) and works with IDEs and static analysers, which makes it the preferred style in modern code.

Older callable forms

Before PHP 8.1 the same thing was written with strings and arrays. You will meet them in older code and in many tutorials:

Form Example Modern equivalent
Function name string 'strtoupper' strtoupper(...)
Static method string 'Formatter::upper' Formatter::upper(...)
Object + method array [$obj, 'format'] $obj->format(...)
Class + method array [Formatter::class, 'upper'] Formatter::upper(...)
Converted to Closure Closure::fromCallable('trim') trim(...)
php · try it yourself
<?php
class Shout
{
    public function make(string $s): string { return strtoupper($s) . "!"; }
    public static function quiet(string $s): string { return strtolower($s) . "..."; }
}

$callables = [
    'string'        => 'ucfirst',
    'static string' => 'Shout::quiet',
    'array (obj)'   => [new Shout(), 'make'],
    'array (class)' => [Shout::class, 'quiet'],
    'fromCallable'  => Closure::fromCallable('strrev'),
];

foreach ($callables as $label => $c) {
    printf("%-14s %-6s %s\n", $label, is_callable($c) ? "yes" : "no", call_user_func($c, "Hello"));
}

var_dump(is_callable('no_such_function'));
string         yes    Hello
static string  yes    hello...
array (obj)    yes    HELLO!
array (class)  yes    hello...
fromCallable   yes    olleH
bool(false)

call_user_func($c, ...$args) calls any callable, and is_callable() checks whether a value can be called. The callable type hint accepts all of these forms.

Tip: Prefer closures, arrow functions and (...) in new code. String callables are invisible to "find usages" in an editor and break silently when a function is renamed.

Test yourself

What is the main difference between fn($x) => $x * $rate and function ($x) { return $x * $rate; }?

  1. Arrow functions are slower
  2. The arrow function captures $rate automatically; the closure needs use ($rate)
  3. Closures cannot take parameters
  4. There is no difference

What does $f = strlen(...); create?

  1. A call to strlen with no arguments
  2. A string 'strlen'
  3. A Closure wrapping strlen
  4. A syntax error

A closure is created with use ($n), then $n changes. What value does the closure see?

  1. The new value
  2. The value at the time the closure was created
  3. null
  4. It throws an error