patternphplaravelTip
PHP 8.1 First-Class Callable Syntax
Viewed 0 times
PHP 8.1+
first-class callableclosurecallable syntaxphp 8.1array_maphigher orderClosure::fromCallable
Problem
Passing methods or functions as callables requires verbose Closure::fromCallable(), string method references, or anonymous function wrappers, making higher-order code noisy.
Solution
Use the first-class callable syntax: Closure::fromCallable() is replaced by simply appending (...) to any callable. Works with functions, static methods, instance methods, and built-in functions: strlen(...), $obj, 'method', ClassName::staticMethod(...).
Why
First-class callables create a Closure from any callable with minimal syntax. The result is a typed Closure that can be passed to array_map, array_filter, or any higher-order function.
Gotchas
- The (...) syntax creates a Closure bound to the object—it captures $this for instance methods at creation time
- Cannot use first-class callables to partially apply arguments—use a closure for currying
- Works with all callables including built-ins: $fn = strlen(...) creates a Closure wrapping strlen
- Nullability: if the object is null you must guard before calling (...)
Code Snippets
First-class callable syntax
// Before PHP 8.1
$lengths = array_map(fn($s) => strlen($s), $strings);
$sorted = usort($items, Closure::fromCallable([$comparator, 'compare']));
// PHP 8.1+
$lengths = array_map(strlen(...), $strings);
$sorted = usort($items, $comparator->compare(...));Revisions (0)
No revisions yet.