First-Class Callables

First-Class Callable Syntax and Callables

A callable is a function name, 'Class::method', a [class, method] or [$object, method] array, an object with __invoke(), or a Closure; the callable type accepts them all. PHP 8.1's first-class callable syntax, strlen(...), $obj->method(...) or Class::method(...), returns a real Closure without calling anything, replacing the string forms and Closure::fromCallable().

Callable forms, a first-class callable and the pipe operatorPHP
<?php
declare(strict_types=1);
final class Text
{
  public static function shout(string $s): string { return strtoupper($s) . '!'; }
  public function __invoke(string $s): string { return "[$s]"; }
}
foreach (['strrev', 'Text::shout', ['Text', 'shout'], new Text(), strrev(...)] as $c) {
  echo get_debug_type($c), ':', $c('Hi'), ' ';
}
echo "\n", ' Hello ' |> trim(...) |> strrev(...) |> Text::shout(...), "\n";  // 8.5 pipe
Output
string:iH string:HI! array:HI! Text:[Hi] Closure:iH
OLLEH!

A misspelled string callable fails only when something calls it; a misspelled no_such_function(...) fails at once with Call to undefined function no_such_function(), and IDEs flag it first. The 8.5 pipe operator (The Pipe Operator) takes first-class callables on its right.