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 attributesfinal class Locale{ #[Validator\Custom(static function (string $languageCode): bool { return \preg_match('/^[a-z][a-z]$/', $languageCode); })] public string $languageCode;} // Closures in sub-expressionsfunction 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