Jump24 - Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

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
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
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
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Debounceable Queued Jobs in Laravel 13.6.0 image

Debounceable Queued Jobs in Laravel 13.6.0

Read article
Build Custom Middleware for Query Performance Monitoring and Optimization in Laravel with MongoDB image

Build Custom Middleware for Query Performance Monitoring and Optimization in Laravel with MongoDB

Read article
Laravel API Starter Kits Are Coming Soon! image

Laravel API Starter Kits Are Coming Soon!

Read article
An Opinionated Agent Skill for Building REST APIs in Laravel image

An Opinionated Agent Skill for Building REST APIs in Laravel

Read article
Launch Your Dream SaaS Application with SaaSykit image

Launch Your Dream SaaS Application with SaaSykit

Read article
Spatie Shares Their Coding Guidelines as AI Skills image

Spatie Shares Their Coding Guidelines as AI Skills

Read article