Get expert guidance in a few days with a Laravel code review

Support for Closures in Constant Expressions in PHP 8.5

Published on by

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:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

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

Visit Laravel Cloud
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum

The latest

View all →
DHH Joins Laravel Live Denmark 2026 for Fireside Chat with Taylor Otwell image

DHH Joins Laravel Live Denmark 2026 for Fireside Chat with Taylor Otwell

Read article
Model-Based Scheduling for Laravel with Cadence image

Model-Based Scheduling for Laravel with Cadence

Read article
Laravel's AI SDK adds sub-agents image

Laravel's AI SDK adds sub-agents

Read article
Laravel Introduces First-Party Passkey Authentication Support image

Laravel Introduces First-Party Passkey Authentication Support

Read article
Scrollbar Styling and Container Size Utilities in Tailwind CSS v4.3.0 image

Scrollbar Styling and Container Size Utilities in Tailwind CSS v4.3.0

Read article
Attach Addresses to Any Eloquent Model with Laravel Addressable image

Attach Addresses to Any Eloquent Model with Laravel Addressable

Read article