First-class callable syntax

suggest change

PHP 8.1 added a short way to turn any function or method into a Closure object: write the call with ... as the only argument.

$len = strlen(...);           // function
$greet = $greeter->greet(...); // instance method
$make = User::make(...);      // static method
$again = $closure(...);       // anything callable stored in a variable

Nothing is called at that point. strlen(...) doesn't run strlen(); it gives you a Closure that will call strlen() later. The ... is part of the syntax and doesn't mean "spread" or "variadic" here.

Before PHP 8.1 you passed functions around as strings ('strlen'), arrays ([$this, 'method']) or with Closure::fromCallable(). The new syntax replaces all three. It's shorter, it fails immediately when the function doesn't exist, it works with private methods, and IDEs, static analyzers and refactoring tools understand it.

All examples were run with PHP 8.5. In error messages, paths are shortened to /app/.

For callables in general see Callable and Passing a callback function as a parameter. For anonymous functions and use see Closures and Anonymous function.

PHP 8.5's pipe operator is built around this syntax: $s |> trim(...) |> strtolower(...) passes a value through a chain of first-class callables.

Creating a closure from a function

<?php
$len = strlen(...);

var_dump($len);
echo get_debug_type($len), "\n";
echo $len('hello'), "\n";

Output:

object(Closure)#1 (2) {
  ["function"]=>
  string(6) "strlen"
  ["parameter"]=>
  array(1) {
    ["$string"]=>
    string(10) "<required>"
  }
}
Closure
5

The result is an ordinary Closure, the same class you get from function () {} or fn() =>. It keeps the original function's signature: parameter names, types, defaults and return type. So you can call it with named arguments, and reflection reports the real parameters. See Named and optional parameters ("Callbacks and dynamic calls").

The most common use is passing a built-in or your own function as a callback:

<?php
$words = ['  apple ', ' banana', 'cherry  '];
print_r(array_map(trim(...), $words));

print_r(array_filter(['1', 'x', '2.5', ''], is_numeric(...)));

$versions = ['10', '9', '100'];
usort($versions, strcmp(...));
echo implode(' ', $versions), "\n";
usort($versions, strnatcmp(...));
echo implode(' ', $versions), "\n";

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)
Array
(
    [0] => 1
    [2] => 2.5
)
10 100 9
9 10 100

Compare with the string form array_map('trim', $words) from Using built-in functions as callbacks. Both work, but 'trim' is just a string: PHP only finds out that it names a function when the callback is called, and an IDE can't jump to it or rename it.

All the forms

Any expression you could call can be turned into a closure by replacing the arguments with ...:

<?php
class Greeter
{
    public function __construct(private string $greeting) {}

    public function greet(string $name): string
    {
        return "$this->greeting, $name!";
    }

    public static function shout(string $s): string
    {
        return strtoupper($s) . '!';
    }

    public function __invoke(string $name): string
    {
        return $this->greet($name);
    }
}

$g = new Greeter('Hello');

$greet = $g->greet(...);        // instance method, bound to $g
$shout = Greeter::shout(...);   // static method
$invoke = $g(...);              // invokable object (__invoke)
$name = 'strtoupper';
$upper = $name(...);            // function name in a variable
$pair = [$g, 'greet'];
$fromArray = $pair(...);        // array callable in a variable

echo $greet('Ann'), "\n";
echo $shout('hey'), "\n";
echo $invoke('Bob'), "\n";
echo $upper('abc'), "\n";
echo $fromArray('Cy'), "\n";

$double = fn(int $x): int => $x * 2;
var_dump($double(...) === $double);

Output:

Hello, Ann!
HEY!
Hello, Bob!
ABC
Hello, Cy!
bool(true)

$closure(...) on something that is already a Closure returns the same object, as the last line shows. On a string, array or invokable object it converts the value to a Closure. So $callable(...) is a handy way to normalize any callable you receive into a Closure:

public function __construct(callable $formatter)
{
    $this->formatter = $formatter(...); // property can be typed Closure
}

Composition and delegation uses this to store strategies in a Closure property. Properties can't have the callable type, but they can be typed Closure.

What is not allowed

A few expressions look like calls but can't be turned into closures. These are compile-time errors, so the whole file fails to load:

$make = new Foo(...);    // Fatal error: Cannot create Closure for new expression
$m = $obj?->method(...); // Fatal error: Cannot combine nullsafe operator with Closure creation
$f = isset(...);         // Parse error: syntax error, unexpected token "..."
$f = echo(...);          // Parse error: syntax error, unexpected token "echo"
$f = str_repeat('x', ...); // Parse error: syntax error, unexpected token ")"

Errors are raised when the closure is created

A string or array callable is just data. PHP doesn't check it until something tries to call it, which may happen much later and far from the typo:

<?php
function showHome(): string { return 'home page'; }
function showAbout(): string { return 'about page'; }

$routes = [
    '/'      => 'showHome',
    '/about' => 'showAbuot', // typo
];

echo "routes loaded\n";
foreach (['/', '/about'] as $path) {
    try {
        echo $routes[$path](), "\n";
    } catch (Error $e) {
        echo 'line ', $e->getLine(), ': ', $e->getMessage(), "\n";
    }
}

try {
    $routes = [
        '/'      => showHome(...),
        '/about' => showAbuot(...),
    ];
} catch (Error $e) {
    echo 'line ', $e->getLine(), ': ', $e->getMessage(), "\n";
}

Output:

routes loaded
home page
line 13: Call to undefined function showAbuot()
line 22: Call to undefined function showAbuot()

With the string, the routes table loads fine and the error only shows up when someone visits /about, pointing at the line that calls the route. With showAbuot(...) the error is thrown on the line with the typo, as soon as the table is built.

The same applies to methods and classes. The exception is the same Error you'd get from calling the missing function directly:

<?php
class Report
{
    public function render(): string { return 'report'; }
}

$r = new Report();

$attempts = [
    'missing method'        => fn() => $r->rendr(...),
    'missing static method' => fn() => Report::create(...),
    'missing class'         => fn() => Missing::create(...),
    'missing function'      => fn() => strlenn(...),
    'non-static as static'  => fn() => Report::render(...),
];

foreach ($attempts as $what => $attempt) {
    try {
        $attempt();
    } catch (Error $e) {
        printf("%-22s %s: %s\n", $what, $e::class, $e->getMessage());
    }
}

Output:

missing method         Error: Call to undefined method Report::rendr()
missing static method  Error: Call to undefined method Report::create()
missing class          Error: Class "Missing" not found
missing function       Error: Call to undefined function strlenn()
non-static as static   Error: Non-static method Report::render() cannot be called statically

Because the method name is written as code and not as a string, static analyzers (PHPStan, Psalm) and IDEs check it, find its usages and rename it. With [$this, 'render'] they have to guess that the string is a method name.

Magic methods are the exception. If the class has __call() or __callStatic(), any method name is accepted and the closure forwards the call:

<?php
class Proxy
{
    public function __call(string $name, array $args): string
    {
        return "__call($name, " . implode(', ', $args) . ')';
    }

    public static function __callStatic(string $name, array $args): string
    {
        return "__callStatic($name)";
    }
}

$anything = (new Proxy())->anything(...);
echo $anything(1, 2), "\n";

$whatever = Proxy::whatever(...);
echo $whatever(), "\n";

Output:

__call(anything, 1, 2)
__callStatic(whatever)

Scope and visibility: passing private methods

A closure created with ... captures the scope where it was created. Inside a class you can create a closure from a private or protected method and hand it to code outside the class, such as array_map(), a framework or an event dispatcher. The closure can be called from anywhere:

<?php
class Slugger
{
    public function slugs(array $titles): array
    {
        return array_map($this->slugify(...), $titles);
    }

    public function asClosure(): Closure
    {
        return $this->slugify(...);
    }

    public function asArrayCallable(): callable
    {
        return [$this, 'slugify'];
    }

    private function slugify(string $title): string
    {
        return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($title)), '-');
    }
}

$s = new Slugger();
print_r($s->slugs(['Hello World', 'PHP 8.1 is out!']));

$fn = $s->asClosure();
echo $fn('Called from outside'), "\n";

$cb = $s->asArrayCallable();
var_dump(is_callable($cb));
try {
    echo $cb('Array callable'), "\n";
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

try {
    $direct = $s->slugify(...);
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

Array
(
    [0] => hello-world
    [1] => php-8-1-is-out
)
called-from-outside
bool(false)
Call to private method Slugger::slugify() from global scope
Call to private method Slugger::slugify() from global scope

Look at the difference:

This is what makes the syntax useful for callbacks: helper methods stay private and you don't have to make them public just so that usort() or a signal handler can call them.

Comparison with Closure::fromCallable()

Closure::fromCallable() (PHP 7.1) did the same thing before the new syntax. It also captures the scope of the caller, so it works with private methods:

<?php
class Price
{
    public function __construct(private float $rate) {}

    public function callbacks(): array
    {
        return [
            'array'        => [$this, 'withTax'],
            'fromCallable' => Closure::fromCallable([$this, 'withTax']),
            'first-class'  => $this->withTax(...),
        ];
    }

    private function withTax(float $net): float
    {
        return round($net * (1 + $this->rate), 2);
    }
}

foreach ((new Price(0.2))->callbacks() as $kind => $cb) {
    try {
        $result = array_map($cb, [10, 2.5]);
        printf("%-13s %-8s %s\n", $kind, get_debug_type($cb), json_encode($result));
    } catch (TypeError $e) {
        printf("%-13s %-8s %s\n", $kind, get_debug_type($cb), 'TypeError: ' . $e->getMessage());
    }
}

Output:

array         array    TypeError: array_map(): Argument #1 ($callback) must be a valid callback or null, cannot access private method Price::withTax()
fromCallable  Closure  [12,3]
first-class   Closure  [12,3]

The two closures are equivalent, but $this->withTax(...) is shorter and the method name is code, not a string. When the function doesn't exist, fromCallable() throws TypeError: Failed to create closure from callable: class Report does not have a method "rendr" instead of Error. Use Closure::fromCallable($x) or $x(...) only when the callable comes in as a value.

'strlen', [$obj, 'm'], 'A::m' Closure::fromCallable(...) strlen(...), $obj->m(...)
Type string / array Closure Closure
Checked when called created created
Private methods from outside no yes, if created inside the class yes, if created inside the class
IDE / static analysis guesses guesses full support
Can store in typed property only as string/array/mixed Closure Closure
Available since always PHP 7.1 PHP 8.1

$this, static and parent

A closure from an instance method is bound to that object. It keeps the object alive as long as the closure exists, and it sees later changes to its state:

<?php
class Counter
{
    public int $n = 0;

    public function inc(): int
    {
        return ++$this->n;
    }
}

$c1 = new Counter();
$c2 = new Counter();

$inc = $c1->inc(...);
$inc();
$inc();
echo "c1={$c1->n} c2={$c2->n}\n";

Output:

c1=2 c2=0

Keep this in mind when registering $this->method(...) with a long-lived service such as an event dispatcher: the object can't be garbage collected until the listener is removed. See Memory and garbage collection.

static::method(...) keeps late static binding, and parent::method(...) calls the parent's version. Their string forms 'static::make' and 'parent::label' are deprecated since PHP 8.2:

<?php
class Model
{
    public int $id;

    public static function make(array $row): static
    {
        $m = new static();
        $m->id = $row['id'];
        return $m;
    }

    public static function hydrate(array $rows): array
    {
        return array_map(static::make(...), $rows);
    }

    public function label(): string
    {
        return static::class . " #$this->id";
    }
}

class User extends Model
{
    public function label(): string
    {
        return 'user ' . $this->id;
    }

    public function labels(): array
    {
        return [$this->label(...), parent::label(...)];
    }
}

class Post extends Model {}

$users = User::hydrate([['id' => 1], ['id' => 2]]);
echo get_class($users[0]), ' ', $users[1]->id, "\n";
echo get_class(Post::hydrate([['id' => 3]])[0]), "\n";

[$own, $inherited] = $users[0]->labels();
echo $own(), ' | ', $inherited(), "\n";

Output:

User 2
Post
user 1 | User #1

For static methods, see also Static members ("Static methods as callables").

Callbacks for handlers and listeners

PHP has many functions that register a callback: set_error_handler(), set_exception_handler(), register_shutdown_function(), spl_autoload_register(), pcntl_signal(), ob_start(), header_register_callback(). With ... the handler can be a private method:

<?php
final class App
{
    private array $log = [];

    public function boot(): void
    {
        set_error_handler($this->onError(...));
        set_exception_handler($this->onException(...));
        register_shutdown_function($this->onShutdown(...));
    }

    private function onError(int $errno, string $message, string $file, int $line): bool
    {
        $this->log[] = "error $errno: $message (line $line)";
        return true; // don't run PHP's own handler
    }

    private function onException(Throwable $e): void
    {
        $this->log[] = 'uncaught ' . $e::class . ': ' . $e->getMessage();
    }

    private function onShutdown(): void
    {
        echo implode("\n", $this->log), "\n";
    }
}

(new App())->boot();

echo $undefined;
throw new RuntimeException('boom');

Output:

error 2: Undefined variable $undefined (line 32)
uncaught RuntimeException: boom

Signal handlers on Linux and macOS follow the same pattern. Here onStop() is private and sets a flag that the worker's main loop checks:

pcntl_async_signals(true);
pcntl_signal(SIGTERM, $this->onStop(...));
pcntl_signal(SIGINT, $this->onStop(...));

Signals and graceful shutdown has the full worker built around this.

Typing listeners as Closure

Because a first-class callable is always a Closure, you can type a parameter or property as Closure. Then a wrong value fails where it's registered, not when the event fires:

<?php
final class Events
{
    /** @var array<string, list<Closure>> */
    private array $listeners = [];

    public function on(string $event, Closure $listener): void
    {
        $this->listeners[$event][] = $listener;
    }

    public function emit(string $event, mixed ...$args): void
    {
        foreach ($this->listeners[$event] ?? [] as $listener) {
            $listener(...$args);
        }
    }
}

final class Mailer
{
    public function sendWelcome(string $email): void
    {
        echo "welcome mail to $email\n";
    }
}

$events = new Events();
$mailer = new Mailer();

$events->on('user.created', $mailer->sendWelcome(...));
$events->emit('user.created', 'ann@example.com');

try {
    $events->on('user.created', [$mailer, 'sendWelcome']);
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

welcome mail to ann@example.com
Events::on(): Argument #2 ($listener) must be of type Closure, array given, called in /app/events.php on line 35

Note that $listener(...$args) in emit() is a normal call that spreads arguments. It has values before the .... Only ... on its own creates a closure.

Typing as Closure is stricter than callable: callers must write $x(...) or a closure, not a string or array. In your own code that's usually what you want. For a public library API, accepting callable and converting it with $callable(...) inside is friendlier.

Pitfalls

Every closure is a new object

Each ... expression creates a new Closure. Two closures for the same method compare equal with == but aren't identical (===). Functions that look up a callback you registered earlier, like spl_autoload_unregister(), compare by identity:

<?php
final class Loader
{
    public function load(string $class): void
    {
        echo "trying to load $class\n";
    }
}

$loader = new Loader();

var_dump($loader->load(...) === $loader->load(...));
var_dump($loader->load(...) == $loader->load(...));

// Wrong: registers one Closure, tries to unregister a different one
spl_autoload_register($loader->load(...));
var_dump(spl_autoload_unregister($loader->load(...)));
echo count(spl_autoload_functions()), " autoloader(s)\n";
spl_autoload_unregister(spl_autoload_functions()[0]);

// Right: keep the Closure and pass the same instance both times
$autoload = $loader->load(...);
spl_autoload_register($autoload);
class_exists('Foo');
var_dump(spl_autoload_unregister($autoload));
echo count(spl_autoload_functions()), " autoloader(s)\n";

Output:

bool(false)
bool(true)
bool(false)
1 autoloader(s)
trying to load Foo
bool(true)
0 autoloader(s)

The same applies to event dispatchers that remove listeners by identity: store the closure in a property if you need to remove it later.

Built-in functions reject extra arguments

Some callers pass more arguments than you might expect: array_filter() with ARRAY_FILTER_USE_BOTH passes ($value, $key), array_walk() passes ($value, $key), preg_replace_callback() passes a matches array. A user function ignores extra arguments, but a built-in function throws:

<?php
$data = ['a' => '1', 'b' => 'x', 'c' => '3'];

try {
    print_r(array_filter($data, is_numeric(...), ARRAY_FILTER_USE_BOTH));
} catch (ArgumentCountError $e) {
    echo $e->getMessage(), "\n";
}

print_r(array_filter($data, fn($v, $k) => is_numeric($v) && $k !== 'a', ARRAY_FILTER_USE_BOTH));

Output:

is_numeric() expects exactly 1 argument, 2 given
Array
(
    [c] => 3
)

Worse, an extra argument can fill an optional parameter and silently change the result. trim($value, $key) would use the array key as the list of characters to strip. When in doubt, check what arguments the caller passes and wrap the function in an arrow function that passes exactly what you want.

Closures can't be serialized

A Closure can't be serialized, cached with var_export(), or stored in a session:

<?php
try {
    serialize(strlen(...));
} catch (Exception $e) {
    echo $e::class, ': ', $e->getMessage(), "\n";
}

Output:

Exception: Serialization of 'Closure' is not allowed

If a configuration has to be cached or serialized, such as a route table compiled to a PHP file, store [Controller::class, 'method'] arrays there and convert them with $callable(...) when you need to call them.

Constant expressions (PHP 8.5)

Since PHP 8.5 a first-class callable of a function or static method is allowed in constant expressions: class constants, parameter defaults, property defaults and attribute arguments. Instance methods aren't allowed there, because there's no object at compile time:

<?php
final class Normalizer
{
    public const array STEPS = [trim(...), strtolower(...), self::squash(...)];

    public static function squash(string $s): string
    {
        return preg_replace('/\s+/', ' ', $s);
    }

    public static function run(string $s, array $steps = self::STEPS): string
    {
        foreach ($steps as $step) {
            $s = $step($s);
        }
        return $s;
    }
}

function chars(string $s, Closure $split = str_split(...)): array
{
    return $split($s);
}

echo Normalizer::run("  Hello    WORLD  "), "\n";
echo implode(',', chars('abc')), "\n";

Output:

hello world
a,b,c

On PHP 8.4 and older, this fails with Fatal error: Constant expression contains invalid operations. Use null as the default and $split ??= str_split(...) in the body there.

Summary

Feedback about page:

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



Table Of Contents