PHP 8.6 is out
PHP 8.6.0 came out this morning, right on schedule. It has been a busy autumn for the project team, with the security fixes around PHP2Shell, which I summed up in an earlier post. It's good to see the new version land on time.
I read the official announcement from start to finish. Here is what I take away from it for everyday code, followed by what to look at before upgrading a project.
A question mark in a function call
This is the feature people will talk about most. If you come across substr(?, 4) while reading code, it isn't a typo.
Take a catalog import where product references arrive as SKU-4821. To strip the prefix, until now you would write a small arrow function:
$numeros = array_map(fn (string $ref) => substr($ref, 4), $references);
In PHP 8.6, you can write:
$numeros = array_map(substr(?, 4), $references);
// ['4821', '7310']
The ? marks an argument you will supply later. substr(?, 4) doesn't call substr() yet: PHP creates a closure that waits for the missing string, and array_map() passes it each reference. The documentation calls this partial function application. The ... placeholder leaves all the remaining arguments open.
It will take your eyes a little while to get used to it. But whenever an arrow function was only there to pass an argument along, the short version reads better. The announcement also notes that array_map() is now compiled into a loop when you give it this kind of callback.
clamp(), at last
A paginated API accepts at most 100 products per page. A client asks for 500. Before, you would write something like max(1, min($quantite, 100)), and you always had to read it twice to work out which bound went where.
$parPage = clamp($quantite, 1, 100);
The value, the minimum, the maximum, in the order you would say it out loud. For 500, you get 100. For 25, you keep 25. clamp() accepts any comparable value, not just numbers.
Durations that state their unit
Is a delay set to 250 long? It depends on what the person who wrote the method had in mind. Milliseconds, microseconds, seconds: the int $delai signature doesn't say.
The new \Time\Duration class settles the question at the call site:
use Time\Duration;
$delai = Duration::fromMilliseconds(250);
$maximum = Duration::fromSeconds(30);
$attente = min($delai, $maximum);
time_nanosleep($attente->seconds, $attente->nanoseconds);
Durations can be compared with each other, so min() and clamp() work directly. The class represents elapsed time, as on a stopwatch, with no date or time zone. It doesn't replace DateInterval for calendar calculations. For a timeout, a pause between two retries or a benchmark, it's a perfect fit.
Two small things that lighten the code
readonly properties can now have a default value. No more constructor whose only job is to assign a constant:
final readonly class RegleSlug implements Regle
{
public string $parser = SlugParser::class;
}
The default value counts as the property's initialization, so the constructor can't overwrite it.
PHP also adds the SortDirection enum, with the cases Ascending and Descending. Every library had its own way of expressing sort order: a string, an integer, a boolean, its own enum. With a type provided by the language, a method like trierPar(string $colonne, SortDirection $sens) rejects a wrong argument as soon as it's called, with a clear TypeError.
For those who write servers
Picture a chat server with a thousand connected clients, only a few of whom send a message at any given moment. Until now, PHP offered stream_select(), which relies on select() and rarely handles more than 1024 connections.
The new Io\Poll API waits until streams are ready for reading or writing, using the operating system's own mechanism: epoll on Linux, kqueue on macOS, event ports or WSAPoll elsewhere. It is aimed first at the authors of event loops such as ReactPHP and AMPHP. If you write a typical Laravel or Symfony application, you probably won't touch it directly, but the libraries you use will be able to build on it.
Before moving a project to 8.6
A few changes are worth a look, even if your code doesn't use any of the new features.
The first is the deprecation of return inside a finally block. Such a return overwrites the value returned by the try and swallows the exception that was on its way up. This code, for example, always returns null, even when the read succeeds:
public function lire(string $chemin): ?array
{
try {
return json_decode(file_get_contents($chemin), true, flags: JSON_THROW_ON_ERROR);
} finally {
return null;
}
}
If your tests flag this case, first decide what the method should do when it fails: return null from a catch, or let the exception propagate. Only then move the return.
Sessions are also stricter by default. session.use_strict_mode and session.cookie_httponly are enabled, and session.cookie_samesite is set to Lax. If some JavaScript was reading the session cookie, it won't be able to anymore.
One last, quieter detail: trim(), ltrim() and rtrim() now also strip the form feed character (\f) by default. Little code depends on it, but a test that compares strings byte for byte may notice.
For a project managed with Composer, composer prohibits php 8.6.0 lists the dependencies whose constraints block the upgrade. The full list of changes is in the migration guide and the PHP 8.6.0 changelog.
See also
- PHP 8.6 is out. Here's everything you need to know, Nuno Maduro's video (in English).
- PHP 8.6 : ce qui change vraiment (et ce qui risque de casser), by Pentiminax (in French).
Written by Jatniel, senior full-stack PHP developer.