What's new in PHP 8.6, with code you actually write

· · 7 min read

Lire cet article en français

PHP 8.6 is out today. Its headline feature, partial function application, sounds minor on paper. Yet it changes how you write many small pieces of code, and it finally makes the pipe operator from PHP 8.5 practical. The rest of the release is made of smaller additions, but each one removes a bit of code that every project rewrites.

I compiled PHP 8.6 from the release branch to check every example in this article. Each time, I show the code from before, then the code after.

Partial application: ? instead of an arrow function

How many times have you written an arrow function that only passes its parameter on to another function?

$organic = array_filter($references, fn (string $reference) => str_starts_with($reference, 'ORG-'));
$prices = array_map(fn (float $amount) => sprintf('$%.2f', $amount), $amounts);

In PHP 8.6, you call the function with ? in place of the missing argument. You do not get a result, but a closure that waits for that argument:

$organic = array_filter($references, str_starts_with(?, 'ORG-'));
$prices = array_map(sprintf('$%.2f', ?), $amounts);

The ? can go anywhere in the argument list, and there can be several of them. ... leaves all the remaining arguments open: the strlen(...) syntax from PHP 8.1 becomes a special case of the same idea.

With array_map(), it is also faster. An array_map() whose callback is a partial application is compiled into a foreach loop: no intermediate closure, and no userland function call for each element.

The trap: arguments are evaluated right away

A partial closure is not an arrow function in disguise. The arguments you provide are evaluated when the closure is created, not when it is called:

$log = $this->write(?, date('H:i:s'));

// … ten minutes later
$log('Order confirmed'); // the time is still the one from creation

With fn ($message) => $this->write($message, date('H:i:s')), the time was computed on every call. Switching to partial application freezes the value. The rule to remember: only bind in advance values that do not change (a log level, a separator), and leave a ? for anything that depends on when the call happens.

The PHP 8.5 pipe becomes readable

PHP 8.5 brought the |> operator, which chains function calls. But it only passes one argument to the next function. As soon as a step needed two, you had to write an arrow function, wrapped in parentheses on top of that:

$slug = $title
    |> trim(...)
    |> strtolower(...)
    |> (fn (string $text) => preg_replace('/[^a-z0-9]+/', '-', $text))
    |> (fn (string $text) => trim($text, '-'));

With partial application, each step fits on one line:

$slug = $title
    |> trim(...)
    |> strtolower(...)
    |> preg_replace('/[^a-z0-9]+/', '-', ?)
    |> trim(?, '-');

It is not just shorter. The compiler recognizes a single ? right after |> and compiles the step into a direct call: no closure is created at all, which I checked in the opcodes.

clamp() replaces max(min())

Keeping a value between two bounds used to be written max(0, min(20, $rating)), an expression you have to read twice to know which bound is which. PHP 8.6 adds clamp():

$rating = clamp($rating, min: 0, max: 20);

clamp() compares like min() and max(), so it also works with dates. It throws a ValueError if the lower bound is above the upper one. That is a real safeguard: max(min()) silently returned one of the two bounds. Watch out for paginating an empty list, where the last page is 0 and falls below the lower bound of 1.

Time\Duration: a delay with a unit

$timeout = 30: seconds or milliseconds? The new Time\Duration class carries its unit:

use Time\Duration;

$base = Duration::fromMilliseconds(100);
$delay = min(Duration::fromSeconds(30), $base->multiplyBy(2 ** $attempt));

The object is immutable: add(), sub(), multiplyBy() and divideBy() return a new duration. Comparison operators work, and so do min(), max() and clamp(). Duration::fromIso8601DurationString('PT1M30S') reads a duration written in a configuration file. Only the time part of the ISO 8601 format is accepted: PT36H works, but P1D throws a Time\TimeException.

Readonly properties get default values

Until now, a readonly property could not declare a default value: you had to go through the constructor. In PHP 8.6, it can:

final class Request
{
    public readonly string $method = 'GET';
    public readonly int $attempts = 3;

    public function __construct(public readonly string $url)
    {
    }

    public function withMethod(string $method): static
    {
        return clone($this, ['method' => $method]);
    }
}

Combined with PHP 8.5's clone() with properties, it lets you write a value object with with…() methods and no sprawling constructor.

#[\Override] now works on constants

The #[\Override] attribute (PHP 8.3) guarantees that a method really overrides a parent method. In 8.6, it also applies to class constants:

final class ExcelExport extends Export
{
    #[\Override]
    protected const string DELIMITER = ';';
}

The day the parent class renames DELIMITER, PHP refuses to compile: "ExcelExport::DELIMITER has #[\Override] attribute, but no matching parent constant exists". Without the attribute, the child class would have kept a constant nobody reads anymore, and the export would have silently gone back to the default value.

SortDirection, an enum for the sort direction

A string $direction = 'asc' parameter also accepts 'ASC', 'ascending' or a typo. PHP 8.6 ships a global enum, SortDirection, with two cases: Ascending and Descending. A match on this enum needs no default branch, and an unknown value can no longer make its way into an ORDER BY clause.

Streams can throw exceptions

fopen() on a missing file emits a warning and returns false. You end up with an @ and a check of the return value, or an error handler that converts the warning. PHP 8.6 adds an error mode to stream contexts:

$context = stream_context_create(['stream' => ['error_mode' => StreamErrorMode::Exception]]);

try {
    $file = fopen($path, 'r', false, $context);
} catch (StreamException $error) {
    // $error->getErrors(): the list of errors, each with a code (StreamErrorCode) and the wrapper involved
}

In exception mode, no warning is emitted anymore: your error handler sees nothing. A handy detail: for a missing file, the code is OpenFailed, not NotFound.

Building a URL with UrlBuilder

PHP 8.5 brought the URI extension, which parses URLs according to the WHATWG standard or RFC 3986. PHP 8.6 adds Uri\WhatWg\UrlBuilder, to build a URL piece by piece instead of concatenating strings:

use Uri\WhatWg\UrlBuilder;

$link = new UrlBuilder()
    ->setScheme('https')
    ->setHost('parcels.example')
    ->setPath('/tracking/'.rawurlencode($number))
    ->setQuery(http_build_query(['lang' => 'en']))
    ->build()
    ->toAsciiString();

UrlBuilder encodes what the WHATWG standard requires (a space in the path becomes %20) and throws a Uri\WhatWg\InvalidUrlException if the result is not a valid URL. build() also accepts a base URL, to resolve a relative path the way a browser would.

Be careful: setPath() encodes neither / nor %, and it resolves ..: /tracking/../admin becomes /admin. A segment that comes from the user should therefore still go through rawurlencode().

Reflection understands private(set) and readonly

A home-made hydrator that checks isPublic() before writing a property has been wrong since PHP 8.4: a public private(set) property is public for reading, but not for writing. PHP 8.6 adds ReflectionProperty::isWritable() and isReadable(), which answer for a given scope:

final class Member
{
    public private(set) int $points = 0;
}

$property = new ReflectionProperty($member, 'points');
$property->isPublic();               // true: readable from anywhere
$property->isWritable(null, $member); // false: only the class may write it

The first argument is the scope you write from (null for code outside any class). The second is the object, needed to know whether a readonly property has already been initialized.

What gets deprecated

The list is long. Here is what you will meet most often in existing code:

  • return in a finally block, which silently swallowed the exception in flight;
  • a value returned from __construct() or __destruct(), which PHP ignored anyway;
  • the aliases is_integer(), is_long(), is_double() and doubleval(), to replace with is_int(), is_float() and floatval();
  • spl_object_hash(), to replace with spl_object_id(), or with a WeakMap to attach data to an object;
  • the third argument of define(), the sorting methods of ArrayIterator (asort(), ksort()…) and the CSV methods of SplFileObject (fgetcsv(), fputcsv()).

A deprecation breaks nothing today, but it announces a removal in a future major version. Run your tests with error_reporting=E_ALL to see them. Some of them (return in finally) are emitted at compile time, before the code even runs: with OPcache, they only show up the first time the file is compiled.

To practice

Each of these features will get its own exercise in the Practice section, in plain PHP, starting on 4 December: you start from code as it is written today, and rewrite it with PHP 8.6. They will appear one by one in the Practice exercises.

← All articles