NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

PHP 8.6: Partial Application, Duration and clamp() in Practice

PHP 8.6 lets you leave arguments as ? and get a closure back. Build a typed retry helper with Time\Duration and clamp(), catch stream errors as exceptions, and find the deprecations that will show up after you upgrade.

Updated Dec 2, 20268 min readIntermediatephp 8.6.0 · php 8.5.13 · docker 28.4

PHP 8.6 came out on November 19, 2026. The headline feature is partial function application: write a call, leave some arguments as ?, and you get back a closure instead of a result. It also adds a Time\Duration class, a clamp() function, stream errors you can catch as exceptions, and a built-in SortDirection enum.

This guide runs each feature in a small script, builds a retry-delay helper that combines three of them, and then covers the deprecations most likely to show up in your logs after the upgrade.

1. Run PHP 8.6 without installing it

The official Docker image is the quickest way to try a new release next to the version you already have. Every script below was run like this:

terminal
docker run --rm php:8.6.0-cli-alpine php -v
text
PHP 8.6.0 (cli) (built: Nov 19 2026 15:19:09) (ZTS)
Copyright © The PHP Group and Contributors
Built by https://github.com/docker-library/php
Zend Engine v4.6.0, Copyright © Zend by Perforce
    with Zend OPcache v8.6.0, Copyright ©, by Zend by Perforce

To run a file from the current folder, mount it:

terminal
docker run --rm -v "$PWD":/app -w /app php:8.6.0-cli-alpine php pfa.php

2. Partial function application

A ? in a call stands for exactly one missing argument. ... stands for all the remaining ones. When a call has a placeholder, PHP doesn't run the function. It returns a Closure that takes the missing arguments.

pfa.php
<?php
$versions = ['8.4', '8.5', '8.6', '8.7'];

// ? fills exactly one argument. The result is a Closure.
$atLeast86 = version_compare(?, '8.6', '>=');
var_dump(array_values(array_filter($versions, $atLeast86)));

// Named placeholders let you reorder parameters.
$strip = str_replace(subject: ?, search: ?, replace: '');
var_dump($strip('2026-12-02', '-'));

// Partial application gives the pipe operator its one-argument callables.
echo ' w3 tutorials ' |> trim(...) |> str_replace(' ', '-', ?) |> strtoupper(...), "\n";
text
array(2) {
  [0]=>
  string(3) "8.6"
  [1]=>
  string(3) "8.7"
}
string(8) "20261202"
W3-TUTORIALS

Three things to know:

  • Named placeholders reorder parameters. str_replace(subject: ?, search: ?, replace: '') gives a closure whose first parameter is $subject, in the order you wrote them.
  • It pairs with the pipe operator. PHP 8.5 added |>, but every step needed a one-argument callable. Before 8.6, str_replace in a pipe meant writing an arrow function. Now str_replace(' ', '-', ?) is enough.
  • Arguments are evaluated once, when the closure is created. An arrow function like fn($x) => greet($x, now()) calls now() every time. greet(?, now()) calls it once and reuses the value. That is usually what you want for configuration, and a subtle bug if you expected a fresh value per call.

On PHP 8.5 the same file doesn't even parse:

text
Parse error: syntax error, unexpected token "?" in /app/pfa.php on line 5

A few forms are not allowed: new Foo(1, ?), placeholders with the nullsafe operator ?->, and mixing placeholders with ...$array unpacking. The partial function application manual page lists the rules.

3. Durations, clamp() and a retry helper

Timeouts and backoff delays are usually plain integers, and the unit lives in a comment: is 30000 milliseconds or microseconds? Time\Duration makes the unit part of the type. It holds whole seconds plus nanoseconds, it is immutable, and two durations compare with <, > and <=>. Arithmetic operators are not supported, so you use methods like add() and multiplyBy().

The new clamp($value, $min, $max) works with any comparable value, durations included. Put the two together with partial application and you get a retry-delay helper:

duration.php
<?php
use Time\Duration;

function retryDelay(Duration $base, Duration $step, int $attempt): Duration
{
    $delay = $base->add($step->multiplyBy(2 ** $attempt));

    // Durations compare with <, >, min() and the new clamp().
    return clamp($delay, min: Duration::fromMilliseconds(250), max: Duration::fromSeconds(30));
}

// Fix the first two arguments now, pass the attempt later.
$delayFor = retryDelay(Duration::fromSeconds(1), Duration::fromMilliseconds(100), attempt: ?);

foreach ([0, 3, 6, 9] as $attempt) {
    $d = $delayFor($attempt);
    printf("attempt %d: %d.%03ds\n", $attempt, $d->seconds, intdiv($d->nanoseconds, 1_000_000));
}

var_dump(Duration::fromIso8601DurationString('PT1M30S')->seconds);
var_dump(Duration::fromMinutes(2) > Duration::fromSeconds(90));
text
attempt 0: 1.100s
attempt 3: 1.800s
attempt 6: 7.400s
attempt 9: 30.000s
int(90)
bool(true)

Attempt 9 would be 52.2 seconds, so clamp() caps it at 30. A caller of $delayFor can't pass the wrong unit, because the only thing left to pass is the attempt number.

Duration has no days, months or years. A day can be 23 or 25 hours across a daylight saving change, so calendar maths still belongs to DateInterval and DateTimeImmutable. Use Duration for fixed amounts of time: timeouts, benchmarks, cache lifetimes. See the Time\Duration class reference and the clamp() docs.

4. Catch stream errors as exceptions

Until now, a failed file_get_contents() emitted a warning and returned false. Getting the reason meant @ plus error_get_last() and parsing a message string. In PHP 8.6 a stream context can ask for exceptions instead:

streams.php
<?php
$context = stream_context_create([
    'stream' => ['error_mode' => StreamErrorMode::Exception],
]);

try {
    file_get_contents('/etc/app/config.json', context: $context);
} catch (StreamException $e) {
    foreach ($e->getErrors() as $error) {
        echo $error->code->name, ' | ', $error->wrapperName, ' | ', $error->message, "\n";
    }
}
text
OpenFailed | plainfile | Failed to open stream: No such file or directory

$error->code is a StreamErrorCode enum case, so you can match on it instead of matching message text. StreamErrorMode::Silent turns off both warnings and exceptions, and the errors are then available from stream_last_errors().

The default is still StreamErrorMode::Error, the old warning behaviour, so existing code doesn't change. The option only works on a context you pass in: stream_context_set_default() rejects it. Details are in stream error handling.

5. SortDirection and readonly defaults

Libraries have long expressed sort order as SORT_ASC, 'desc', true or their own enum. PHP 8.6 ships a shared SortDirection enum with Ascending and Descending cases. Readonly properties can also declare a default value now, which removes constructors that exist only to assign a constant.

types.php
<?php
interface Rule
{
    public string $parser { get; }
}

// A readonly property can now have a default value.
final readonly class SlugRule implements Rule
{
    public string $parser = 'slug';
}

function sortNames(array $names, SortDirection $direction = SortDirection::Ascending): array
{
    usort($names, fn ($a, $b) => match ($direction) {
        SortDirection::Ascending => $a <=> $b,
        SortDirection::Descending => $b <=> $a,
    });
    return $names;
}

echo (new SlugRule())->parser, "\n";
echo implode(', ', sortNames(['mia', 'ali', 'zoe'], SortDirection::Descending)), "\n";

try {
    sortNames(['mia', 'ali'], SORT_DESC);
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}
text
slug
zoe, mia, ali
sortNames(): Argument #2 ($direction) must be of type SortDirection, int given, called in /app/types.php on line 26

With an int parameter, SORT_STRING would have been accepted and failed later inside the method. With the enum, the wrong value fails at the call site. The readonly default counts as the property's initialization, so a constructor can't overwrite it. If the value depends on constructor input, keep assigning it in the constructor.

6. What to check before you upgrade

Most of the changes are deprecations, which emit E_DEPRECATED but keep working. A few behaviour changes are silent, so test them. This script runs on both versions:

upgrade.php
<?php
function load(): string
{
    try {
        throw new RuntimeException('database is down');
    } finally {
        return 'cached'; // swallows the exception
    }
}
echo load(), "\n";

var_dump(trim("\fcsv value\f"));
var_dump(is_integer(5));
echo ini_get('session.use_strict_mode'), ' ', ini_get('session.cookie_httponly'), ' ', ini_get('session.cookie_samesite'), "\n";

PHP 8.5.13:

text
cached
string(11) "csv value"
bool(true)
0 0 

PHP 8.6.0:

text
Deprecated: Returning from a finally block is deprecated in /app/upgrade.php on line 7
cached
string(9) "csv value"

Deprecated: Function is_integer() is deprecated since 8.6, use is_int() instead in /app/upgrade.php on line 13
bool(true)
1 1 Lax

What changed:

  • return inside finally is deprecated. It silently throws away the exception, as load() shows: the database error disappears. Move the fallback into a catch block.
  • trim(), ltrim() and rtrim() now strip form feeds (\f). The string went from 11 to 9 bytes. This matters if you parse fixed-width or legacy text files that use \f as a page break.
  • Aliases are deprecated. is_integer(), is_long(), is_double() and doubleval() should become is_int(), is_float() and floatval(). spl_object_hash() should become spl_object_id().
  • Sessions are stricter by default. session.use_strict_mode and session.cookie_httponly are on, and session.cookie_samesite is Lax. That is safer, but JavaScript that reads the session cookie, or a cross-site POST flow that relies on it, will break. Set the old values in php.ini only if you really need them.
  • fclose(), file_put_contents() and copy() return false when the final flush fails. Code that ignored those return values was hiding failed writes.
  • The mb_ereg* functions are deprecated. Switch to preg_* with the u modifier.

Run your test suite with error_reporting=E_ALL on 8.6 and fix the deprecations while they are still only warnings. The full lists are in the deprecated features and backward incompatible changes pages.

When not to rush

PHP 8.6.0 is a .0 release. Frameworks, extensions and static analysers need time to support the new syntax, and a tool that can't parse ? placeholders will fail on any file that uses them. Upgrade the runtime first and keep your code 8.5-compatible. Start using partial application and Duration once your CI tools understand them.

PHP 8.2 through 8.5 are still supported, so nothing forces a move this week. The deprecation warnings are worth collecting now, though, because deprecated features are the ones a future major version can remove.

Next steps

  • Read the PHP 8.6 release announcement for the smaller additions: URI builders, post-quantum key encapsulation in Sodium, and #[\Override] on class constants.
  • Work through the PHP 8.6 migration guide with your test suite running.
  • If you maintain an event loop or async library, read the Polling API RFC. Io\Poll uses epoll or kqueue instead of stream_select().
  • Try the SortDirection enum in a query builder or repository API you own.

Related tutorials