Skip to content
Home
Software

What’s New in PHP 8.6: Features, Code Examples and a Migration Guide

Sinan Eldem

• 14 min read

What’s New in PHP 8.6: Features, Code Examples and a Migration Guide

PHP 8.6 was released on November 19, 2026. Led by partial function application, which changes the way we work with functions, this release adds long-missing pieces for everyday work such as time, streams and error handling to the standard library. In this article you will find all the notable changes organized by topic, with code examples, deprecations and migration advice.

Key Features

The headline features of PHP 8.6 are:

  • Partial Function Application

  • The new \Time\Duration class

  • The polling API (Io\Poll)

  • Stream error handling

  • The new clamp() function

  • The new SortDirection enum

  • DocComments for function parameters

  • ReflectionProperty::isReadable() and isWritable()

  • Default values for readonly properties

Let’s go through them one by one.

1. Partial Function Application

You can provide some of a function’s arguments in advance and leave the rest open with the ? and ... placeholders. The result is a Closure; the function only runs once the remaining arguments are passed.

Why does it matter?

  • No more short arrow functions (fn ($x) => ...) whose only job is to pass one argument along.

  • Code with callback-taking functions such as array_map() and array_filter() becomes shorter and easier to read.

  • It works with named arguments: you can leave just one parameter open, such as attempt: ? (see the Duration example).

PHP 8.5 and older:

$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];

$supportsPfa = array_filter(
    $versions,
    fn ($version) => version_compare($version, '8.6', '>='),
);

With PHP 8.6:

$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];

$supportsPfa = array_filter(
    $versions,
    version_compare(?, '8.6', '>='),
);

Here version_compare(?, '8.6', '>=') produces a closure waiting for its first argument, and array_filter() fills that slot with each element.

RFC: wiki.php.net/rfc/partial_function_application_v2

2. The New \Time\Duration Class

A new value class for elapsed time as measured by a stopwatch. It is independent of dates and time zones and covers a range of more than 250 years with nanosecond precision. It is designed for timeouts and benchmark timings.

Why does it matter?

  • No more “is this number microseconds or milliseconds?”: the unit lives in the type.

  • Durations are comparable, so min(), max() and the new clamp() work directly.

  • Methods such as add() and multiplyBy() make the arithmetic safe.

PHP 8.5 and older:

/**
 * All delays are in microseconds.
 */
function backoff(
    int $baseDelay,
    int $step,
    int $attempt,
): void {
    $delay = $baseDelay + ($step * (2 ** $attempt));

    // Wait at most 30 seconds.
    usleep(min($delay, 30_000_000));
}

// 1 second base delay, plus 100 milliseconds
// doubling with each attempt.
backoff(1_000_000, 100_000, $attempt);

With PHP 8.6:

use Time\Duration;

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

    // Durations are comparable, so min() works directly.
    $delay = min($delay, Duration::fromSeconds(30));

    time_nanosleep($delay->seconds, $delay->nanoseconds);
}

backoff(
    Duration::fromSeconds(1),
    Duration::fromMilliseconds(100),
    $attempt,
);

// Preconfigure the delays using Partial Function Application.
$waitBeforeRetry = backoff(
    Duration::fromSeconds(1),
    Duration::fromMilliseconds(100),
    attempt: ?,
);
$waitBeforeRetry($attempt);

Note how partial function application is used at the end to produce a $waitBeforeRetry function with the delays already configured.

RFC: wiki.php.net/rfc/duration_class

3. The Polling API (Io\Poll)

The new Io\Poll API monitors many streams at once. Depending on the platform it uses epoll, kqueue, event ports or WSAPoll, without the scalability limits of stream_select(). It is designed as a foundation for event loop libraries such as ReactPHP and AMPHP.

Why does it matter?

  • The select()-based approach typically could not handle more than 1024 connections.

  • Long-running servers, websockets and queue workers benefit directly.

  • Instead of rebuilding and searching arrays on every loop, each watched resource is managed through a watcher object.

PHP 8.5 and older:

$server = stream_socket_server('tcp://0.0.0.0:8080');
$clients = [];

while (true) {
    $read = [$server, ...$clients];
    $write = $except = null;

    // Based on select(), which typically can't handle
    // more than 1024 connections
    stream_select($read, $write, $except, null);

    foreach ($read as $stream) {
        if ($stream === $server) {
            $clients[] = stream_socket_accept($server);
            continue;
        }

        $data = fread($stream, 8192);

        if ($data === '' || $data === false) {
            $key = array_search($stream, $clients, true);
            unset($clients[$key]);
            fclose($stream);
        } else {
            fwrite($stream, $data);
        }
    }
}

With PHP 8.6:

use Io\Poll\{Context, Event};

$server = stream_socket_server('tcp://0.0.0.0:8080');

// Automatically uses epoll, kqueue, event ports, or WSAPoll
$poll = new Context();
$poll->add(new StreamPollHandle($server), [Event::Read]);

while (true) {
    foreach ($poll->wait() as $watcher) {
        $stream = $watcher->getHandle()->getStream();

        if ($stream === $server) {
            $client = stream_socket_accept($server);
            $poll->add(
                new StreamPollHandle($client),
                [Event::Read],
            );
            continue;
        }

        $data = fread($stream, 8192);

        if ($data === '' || $data === false) {
            $watcher->remove();
            fclose($stream);
        } else {
            fwrite($stream, $data);
        }
    }
}

RFC: wiki.php.net/rfc/poll_api

4. Stream Error Handling

Stream operations can now be configured to throw a StreamException or fail silently instead of emitting warnings. Errors are structured StreamError objects with a StreamErrorCode enum case, the wrapper name and the path or URL. They can also be retrieved with stream_last_errors() or a custom error handler.

Why does it matter?

  • The era of the @ operator and unstructured text from error_get_last() is over.

  • Deciding by error type (missing file? no permission?) no longer requires parsing a message.

PHP 8.5 and older:

$config = @file_get_contents('/etc/app/config.json');

if ($config === false) {
    // Only an unstructured message string is available
    $error = error_get_last();
    log_error($error['message']);
}

With PHP 8.6:

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

try {
    $config = file_get_contents(
        '/etc/app/config.json',
        context: $context,
    );
} catch (StreamException $e) {
    foreach ($e->getErrors() as $error) {
        // $error->code is a StreamErrorCode enum case
        log_error(
            $error->code->name,
            $error->message,
            $error->wrapperName,
        );
    }
}

RFC: wiki.php.net/rfc/stream_errors

5. The New clamp() Function

Keeps a value (a number or any comparable value) within a given range; if it falls outside, the nearest boundary is returned.

Why does it matter?

  • It replaces hard-to-read patterns such as max(0, min($x, 100)).

  • With the named min: and max: arguments its intent is clear at a glance.

  • It also works with comparable objects such as Duration.

PHP 8.5 and older:

var_dump(max(0, min(-10, 100)));
// int(0)

var_dump(max(0, min(50, 100)));
// int(50)

var_dump(max(0, min(110, 100)));
// int(100)

With PHP 8.6:

var_dump(clamp(-10, 0, 100));
// int(0)

var_dump(clamp(50, 0, 100));
// int(50)

var_dump(clamp(110, 0, 100));
// int(100)

// Any comparable value works with clamp(). This
// includes the new Duration class.
var_dump(clamp(
    \Time\Duration::fromSeconds(30),
    min: \Time\Duration::fromMinutes(1),
    max: \Time\Duration::fromMinutes(10),
)->seconds);
// int(60)

RFC: wiki.php.net/rfc/clamp_v2

6. The New SortDirection Enum

A shared, type-safe enum that expresses sort order with the Ascending and Descending cases. Libraries can accept it in their public APIs without adapter code.

Why does it matter?

  • int constants (SORT_ASC) were accepted by the signature and then failed inside the method; with the enum a wrong value fails with a TypeError at the call.

  • Query builders, collections and API clients can share one contract.

PHP 8.5 and older:

class QueryBuilder
{
    private array $orderBy = [];

    public function orderBy(
        string $column,
        int $direction = SORT_ASC,
    ): static {
        $this->orderBy[] = $column . ' ' . match ($direction) {
            SORT_ASC => 'ASC',
            SORT_DESC => 'DESC',
        };

        return $this;
    }
}

$qb->orderBy('name', SORT_DESC);
$qb->orderBy('name', SORT_STRING);
// Accepted by the signature, then fails inside the method:
// UnhandledMatchError: Unhandled match case 2

With PHP 8.6:

class QueryBuilder
{
    private array $orderBy = [];

    public function orderBy(
        string $column,
        SortDirection $direction = SortDirection::Ascending,
    ): static {
        $this->orderBy[] = $column . ' ' . match ($direction) {
            SortDirection::Ascending => 'ASC',
            SortDirection::Descending => 'DESC',
        };

        return $this;
    }
}

$qb->orderBy('name', SortDirection::Descending);
$qb->orderBy('name', SORT_STRING);
// TypeError: QueryBuilder::orderBy(): Argument #2 ($direction)
// must be of type SortDirection, int given

RFC: wiki.php.net/rfc/sort_direction_enum

7. DocComments for Function Parameters

Function and method parameters can now have their own DocComments, which can be read with the new ReflectionParameter::getDocComment() method.

Why does it matter?

  • The description sits right next to the parameter; no more matching names against @param lines.

  • Documentation generators, API schema tools and IDEs can read parameter descriptions straight from Reflection.

PHP 8.5 and older:

class DB
{
    /**
     * Returns up to $limit items matching the $query.
     *
     * @param string $query Terms to search
     * @param int $limit Maximum number of results
     */
    public function search(string $query, int $limit = 10): array
    {
        return [];
    }
}

// Parameter descriptions can only be extracted
// by parsing the function's DocComment.

With PHP 8.6:

class DB
{
    /**
     * Returns up to $limit items matching the $query.
     */
    public function search(
        /** Terms to search */
        string $query,

        /** Maximum number of results */
        int $limit = 10,
    ): array {
        return [];
    }
}

var_dump(
    new ReflectionParameter([DB::class, 'search'], 'query')
        ->getDocComment(),
);
// string(22) "/** Terms to search */"

RFC: wiki.php.net/rfc/parameter-doccomments

8. ReflectionProperty::isReadable() and isWritable()

These tell whether a property can be read or written from a given scope, and optionally for a specific object, taking visibility, initialization state, property hooks and magic methods into account.

Why does it matter?

  • With asymmetric visibility such as private(set) and hooks, answering this by hand had become hard.

  • Directly useful for serializers, form hydrators and ORMs.

With PHP 8.6:

class NewsEntry
{
    public string $title = 'PHP 8.6 released!';

    public private(set) string $slug = 'php-86-released';
}

$entry = new NewsEntry();
foreach (['title', 'slug'] as $item) {
    $property = new ReflectionProperty(NewsEntry::class, $item);
    printf(
        "%s: isReadable=%s isWritable=%s\n",
        $item,
        $property->isReadable(null, $entry) ? 'yes' : 'no',
        $property->isWritable(null, $entry) ? 'yes' : 'no',
    );
}
// title: isReadable=yes isWritable=yes
// slug: isReadable=yes isWritable=no

RFC: wiki.php.net/rfc/isreadable-iswriteable

9. Default Values for Readonly Properties

Instance readonly properties, including those in readonly classes, can now declare a default value. The default counts as initialization, so the constructor cannot overwrite it.

Why does it matter?

  • No need to write a constructor just to assign a constant value.

  • Property hook contracts from an interface can be met in a single line.

PHP 8.5 and older:

interface Rule
{
    public string $parser { get; }
}

final readonly class SlugRule implements Rule
{
    public string $parser;

    public function __construct()
    {
        $this->parser = SlugParser::class;
    }
}

With PHP 8.6:

interface Rule
{
    public string $parser { get; }
}

final readonly class SlugRule implements Rule
{
    public string $parser = SlugParser::class;
}

RFC: wiki.php.net/rfc/readonly_property_defaults

Other Improvements

  • #[\Override] can now be applied to class constants and enum cases.

  • Enums can implement the __debugInfo() magic method.

  • Properties of objects stored in constants can be modified directly (e.g. Config::DEFAULTS->timeout = 30).

  • The URI extension gains Uri\Rfc3986\UriBuilder and Uri\WhatWg\UrlBuilder, methods to detect URI and host types, and the Uri\WhatWg\url_percent_encode() function.

  • Sodium supports post-quantum key encapsulation (X-Wing and ML-KEM-768), IP address encryption, and the SHAKE / TurboSHAKE functions.

  • TLS streams support session resumption, external pre-shared keys and TLS 1.3 early data (0-RTT).

  • The new mysqli::quote_string() method escapes a string and wraps it in quotes, like PDO::quote().

  • pack() and unpack() accept the < and > endianness modifiers on integer and float format codes.

  • JSON error messages include the location of the error in the input.

  • The new error_include_args INI setting consistently includes function arguments in error messages.

  • The new grapheme_strrev() function reverses strings by grapheme cluster; the new IntlNumberRangeFormatter class formats ranges of numbers.

  • ZipArchive::openString() and closeString() work with in-memory archives.

Performance: array_map() calls with first-class callable or partial application callbacks are compiled into loops; printf() is faster, stateless closures are cached and JSON encoding is faster.

Compatibility and Backward-Incompatible Changes

Deprecations

  • Using return inside a finally block.

  • Returning a value from __construct() or __destruct(), or making them generators; a nullable return type for __debugInfo().

  • let or is as a class, function or constant name; _ as a constant name, namespace as a class constant name, readonly as a function name.

  • mbstring regex functions such as mb_ereg() and mb_split() (Oniguruma is no longer maintained); use PCRE with the u modifier.

  • The is_double(), is_long(), is_integer() and doubleval() aliases; use is_float(), is_int(), floatval().

  • spl_object_hash() (use spl_object_id()) and spl_classes() (use ReflectionExtension::getClassNames()).

  • Passing an object where an array is expected to array_walk(), array_walk_recursive(), http_build_query() and similar; call get_object_vars() first.

  • strcoll() and SORT_LOCALE_STRING; use the intl Collator class.

  • A third argument to define(); passing a class-name string to is_a() / is_subclass_of() when $allow_string is false.

  • Custom session handlers that do not implement both create_sid() and validateId().

  • metaphone(), mysqli_get_charset(), mysqli_stmt_init(), the CSV methods of SplFileObject and the sorting, flag and serialization methods of ArrayIterator.

Behaviour Changes

  • Safer session defaults: session.use_strict_mode and session.cookie_httponly are on, and session.cookie_samesite is Lax.

  • trim(), ltrim() and rtrim() also strip the form feed (\f) character by default.

  • fclose(), file_put_contents() and copy() return false when flushing or closing fails.

  • Many functions throw a ValueError for out-of-range values, invalid flags or NUL bytes instead of silently truncating them.

Migration Tips

  • Clear the E_DEPRECATED notices on PHP 8.5 first, then run your tests on 8.6.

  • If you do not set session options explicitly in php.ini, check whether the new SameSite=Lax default affects login flows that come back from third parties (payments, OAuth).

  • Search your code base for mb_ereg*, is_integer(), spl_object_hash() and similar, and move them to their replacements; Rector can automate most of this.

  • In Laravel projects, check your Composer dependencies’ PHP 8.6 support with composer why-not php 8.6.

  • For the full list, see the official migration guide and the ChangeLog.

Conclusion

Rather than one big, flashy feature, PHP 8.6 brings solid building blocks that simplify everyday code. Partial function application noticeably shortens callback-heavy code; Duration, clamp() and SortDirection turn small helpers rewritten in every project into part of the language. Io\Poll and the new stream error handling open the way for long-running PHP applications.

Because of the safer session defaults and the long list of deprecations, I recommend migrating without haste: with tests, and after clearing the notices on 8.5 first.

Source and code examples: the official PHP 8.6 release announcement (php.net).

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more