Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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
PhpStorm logo

PhpStorm

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

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

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

Shift
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
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
Nimbus: An In-Browser API Testing Playground for Laravel image

Nimbus: An In-Browser API Testing Playground for Laravel

Read article
Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout image

Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout

Read article
Handling Large Datasets with Pagination and Cursors in Laravel MongoDB image

Handling Large Datasets with Pagination and Cursors in Laravel MongoDB

Read article
Driver-Based Architecture in Spatie's Laravel PDF v2 image

Driver-Based Architecture in Spatie's Laravel PDF v2

Read article
Why Your Livewire Dashboard Jumps (And How to Fix It) - Laravel In Practice EP18 image

Why Your Livewire Dashboard Jumps (And How to Fix It) - Laravel In Practice EP18

Read article
Laravel Live UK returns to London on June 18-19, 2026 image

Laravel Live UK returns to London on June 18-19, 2026

Read article