First-class Callable Syntax in PHP 8.1

PHP offers Closure::fromCallable static method which allows to create a new anonymous function also known as Closure from specified callback using the current scope.

For example, if we want to return class private method as a callback, we can use Closure::fromCallable as follows:

Validator.php

<?php

class Validator
{
    public function getValidationCallback(): Closure
    {
        return Closure::fromCallable([$this, 'validateData']);
    }

    private function validateData(array $data): void {}
}
<?php

require_once 'Validator.php';

$validator = new Validator();
$callback = $validator->getValidationCallback();
$callback([1, 2, 3]);

Since PHP 8.1, we can use first-class callable syntax for creating a new anonymous function (Closure). Validator class can be rewritten as follows:

Validator.php

<?php

class Validator
{
    public function getValidationCallback(): Closure
    {
        return $this->validateData(...);
    }

    private function validateData(array $data): void {}
}

First-class callable syntax can be used with:

  • Functions
<?php

// Old way
$callback = Closure::fromCallable('strlen');
echo $callback('Hello'); // 5

// New syntax
$callback = strlen(...);
echo $callback('Hello'); // 5
  • Class methods
<?php

class Validator
{
    public function getCallbackA(): Closure
    {
        return Closure::fromCallable([$this, 'validateData']); // Old way
    }

    public function getCallbackB(): Closure
    {
        return $this->validateData(...); // New syntax
    }

    private function validateData(array $data): void {}
}
  • Class static methods
<?php

class Validator
{
    public function getCallbackA(): Closure
    {
        return Closure::fromCallable([Validator::class, 'validateData']); // Old way
    }

    public function getCallbackB(): Closure
    {
        return self::validateData(...); // New syntax
    }

    private static function validateData(array $data): void {}
}

Leave a Comment

Your email address will not be published.