PHP 8.1 – Callable syntax

PHP 8.1 – Callable syntax

linked dots structure

Convert any callable into Closure object to be returned and then used/called when needed. The next syntax (aka First class callable syntax) of $this->methodName(...) is identical in behavior as current: Closure::fromCallable([this, 'methodName']). Do not confuse this syntax to unpacking argument syntax of ...$args.

This feature introduce a first-class callable syntax, which supersedes existing encodings using strings and arrays. The advantage is that the new syntax is accessible to static analysis, and respects the scope at the point where the callable is created.

$fn = Closure::fromCallable('strlen');
$fn = strlen(...);
$fn = Closure::fromCallable([$this, 'method']);
$fn = $this->method(...)
$fn = Closure::fromCallable([Foo::class, 'method']);
$fn = Foo::method(...);

In this example, each pair of expressions is equivalent. The strlen(...) syntax creates a Closure that refers to the strlen() function, and so on.

The ... can be seen akin to the argument unpacking syntax ...$args, with the actual arguments not yet filled in:

$fn = Foo::method(...);
// Think of it as:
$fn = fn(...$args) => Foo::method(...$args);

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment