News

Support for Closures in Constant Expressions in PHP 8.5

Published
Support for Closures in Constant Expressions in PHP 8.5 image

PHP 8.5 introduces support for closures in constant expressions, making it possible to define a default attribute value as a Closure, among other use-cases. The RFC introduction explains what this means from the PHP language perspective:

Several PHP constructs are limited to accept “constant expressions” only. These expressions may only contain a limited number of operations that can roughly be summarized as “immutable values”. Notably attribute parameters are a construct that only accepts constant expressions and Closures are not currently part of the set of allowed operations in constant expressions.

As Closures are effectively just PHP source code (or rather: PHP Opcodes) they are an immutable value (when limiting some of the features) and as such there is no fundamental reason why they should not be allowed within constant expressions. And indeed there are some use cases that would be enabled by allowing Closures to appear in constant expressions.

Let's look at an example of what this update introduces for PHP function and method arguments. Instead of requiring a Closure instance to be null and then providing a default, you can define the default value as part of the argument:

function my_array_filter(
    array $array,
    Closure $callback = static function ($item) { return !empty($item); },
) {
    $result = [];
 
    foreach ($array as $item) {
        if ($callback($item)) {
            $result[] = $item;
        }
    }
 
    return $result;
}
 
my_array_filter([
    0, 1, 2,
    '', 'foo', 'bar',
]); // [1, 2, "foo", "bar"]

Before PHP 8.5 comes out, you would need to define the closure as null by default and assign a default Closure if the user does not provide one:

function my_array_filter(array $array, ?Closure $callback = null)
{
    $callback ??= static fn ($item) => !empty($item);
    $result = [];

    foreach ($array as $item) {
        if ($callback($item)) {
            $result[] = $item;
        }
    }

    return $result;
}

While it's not too inconvenient to define a default within the function, there are a few examples that open up possibilities with PHP attributes, among other things:

// Closures in PHP attributes
final class Locale
{
    #[Validator\Custom(static function (string $languageCode): bool {
        return \preg_match('/^[a-z][a-z]$/', $languageCode);
    })]
    public string $languageCode;
}

// Closures in sub-expressions
function foo(
    string $input,
    array $callbacks = [
        static function ($value) {
            return \strtoupper($value);
        },
        static function ($value) {
            return \preg_replace('/[^A-Z]/', '', $value);
        },
    ]
) {
    foreach ($callbacks as $callback) {
        $input = $callback($input);
    }
 
    return $input;
}
 
foo('Hello, World!'); // string(10) "HELLOWORLD"

Learn More

The code for the RFC proposal has already been implemented and merged into the master branch of the PHP source at the time of writing.

To learn more, check out the RFC proposal for full details rfc:closures_in_const_expr and see our post on everything new in PHP 8.5

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article
Real-Time Inertia Props With Laravel Reverb image

Real-Time Inertia Props With Laravel Reverb

Read article