Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
PHP

What's new in PHP 8.6: partial function application, clamp(), Duration and more

PHP 8.6 adds partial function application, clamp(), a Time\Duration class, readonly property defaults and a SortDirection enum, and makes sessions stricter by default. Each feature with a short example, then the behaviour changes and deprecations to fix before upgrading.

Nilesh Kushvaha

8 min read

Cloudsoft Zone cover: What's new in PHP 8.6
Image: Cloudsoft Zone
In this article

PHP 8.6 was released on 19 November 2026. What's new in PHP 8.6 is led by partial function application, a clamp() function, a Time\Duration class, default values for readonly properties and a SortDirection enum, plus two additions aimed at library authors: a polling API and structured stream errors. It also makes sessions stricter by default and deprecates a long list of old functions. PHP 8.6 has active support until 31 December 2028 and security fixes until 31 December 2030.

This guide shows each feature with a short example, then the behaviour changes and deprecations to check before you upgrade. It is written from the official upgrade notes, the release announcement and the RFCs, and the examples follow the syntax documented there. If you run Laravel, the upgrade steps are in upgrading a Laravel app to PHP 8.6.

Partial function application in PHP 8.6

Partial function application lets you supply some arguments of a call now and the rest later. Put ? where one argument is still missing, or ... for "all the arguments I have not given", and PHP returns a Closure instead of calling the function. The function runs only when the closure is called.

PHP
function price(float $net, float $taxRate, int $decimals): string
{
    return number_format($net * (1 + $taxRate), $decimals);
}

// PHP 8.6: one placeholder, so the closure takes one argument.
$withVat = price(?, 0.2, 2);
echo $withVat(100); // 120.00

// PHP 8.5 and older
$withVat = static fn (float $net): string => price($net, 0.2, 2);

// "..." leaves every remaining parameter open.
$forHundred = price(100, ...); // takes $taxRate and $decimals

The closure keeps the names, types and default values of the parameters you left open, so static analysis and reflection still see a typed signature. It works with any callable: functions, methods, static methods and closures.

The feature pays off wherever a callback is expected:

PHP
$ids = ['7', '42', '108'];
$padded = array_map(str_pad(?, 5, '0', STR_PAD_LEFT), $ids);
// ['00007', '00042', '00108']

// With the pipe operator from PHP 8.5
$slug = $title
    |> trim(...)
    |> strtolower(...)
    |> str_replace(' ', '-', ?);

Partial application sits alongside the first-class callable syntax from PHP 8.1, strlen(...), which leaves every argument open. The pipe operator is covered in what's new in PHP 8.5.

clamp(): keep a value inside a range

clamp($value, $min, $max) returns the value if it lies between the two bounds (both inclusive) and the nearest bound otherwise. It replaces the max($min, min($max, $value)) idiom, which is easy to write the wrong way round.

PHP
$page    = clamp((int) ($_GET['page'] ?? 1), 1, 500);
$opacity = clamp($input, min: 0.0, max: 1.0);

clamp(4, 8, 6);
// ValueError: clamp(): Argument #2 ($min) must be smaller than
// or equal to argument #3 ($max)

It follows PHP's normal comparison rules, so it also works with strings and with comparable objects such as DateTimeImmutable and the new Duration. A NAN bound throws a ValueError.

Time\Duration: a type for elapsed time

Timeouts and delays have always been bare integers in PHP, with the unit hidden in a comment or a parameter name. Time\Duration represents elapsed time with nanosecond precision, independent of any date or time zone.

PHP
use Time\Duration;

$timeout = Duration::fromSeconds(30);
$retry   = Duration::fromMilliseconds(250)->multiplyBy(4); // one second
$total   = $timeout->add($retry);

if ($total > Duration::fromMinutes(1)) {
    throw new RuntimeException('Budget exceeded');
}

time_nanosleep($retry->seconds, $retry->nanoseconds);

Durations are comparable, so min(), max() and clamp() accept them directly.

Readonly defaults, SortDirection and #[\Override] on constants

Readonly properties can declare a default value. The default counts as the initialisation, so the constructor cannot overwrite it. Fixed values no longer need a constructor:

PHP
final readonly class ApiVersion
{
    public string $name = 'v2';
    public int $maxPageSize = 100;
}

SortDirection is a built-in enum with the cases Ascending and Descending. Libraries can accept it in their public API instead of a mix of integers, strings and booleans:

PHP
function orderBy(string $column, SortDirection $direction = SortDirection::Ascending): string
{
    return $column . ' ' . match ($direction) {
        SortDirection::Ascending => 'ASC',
        SortDirection::Descending => 'DESC',
    };
}

#[\Override] now works on class constants and enum cases, not only on methods. If the parent constant is renamed or removed, PHP reports an error instead of leaving a constant that silently overrides nothing.

PHP
class Job
{
    public const int MAX_RETRIES = 3;
}

final class ImportJob extends Job
{
    #[\Override]
    public const int MAX_RETRIES = 5;
}

Stream errors you can catch, and a polling API

Stream functions such as file_get_contents() have always reported failure with a warning and false. In PHP 8.6 a stream context can ask for exceptions instead, and each error is a structured object with an enum code:

PHP
$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) {
        $logger->error($error->message, ['code' => $error->code->name]);
    }
}

The new Io\Poll API watches many streams at once using the best mechanism on each platform (epoll, kqueue, event ports or WSAPoll), without the connection limit of stream_select(). Most applications will meet it through event-loop libraries such as ReactPHP and AMPHP, not directly.

What's new in PHP 8.6: smaller additions worth knowing

  • mysqli::quote_string() escapes a string and wraps it in quotes, matching PDO::quote().
  • JSON error messages from json_last_error_msg() and JsonException now include where in the input the error is.
  • pack() and unpack() accept the < and > endianness modifiers on integer and float format codes.
  • Function parameters can carry their own DocComments, read with ReflectionParameter::getDocComment().
  • ReflectionProperty::isReadable() and isWritable() answer whether a property can be read or written from a given scope, which matters now that readonly, asymmetric visibility and hooks exist.
  • grapheme_strrev() reverses a string by grapheme cluster, and IntlNumberRangeFormatter formats ranges of numbers.
  • ZipArchive::openString() and closeString() work with archives held in memory.
  • The Sodium extension adds post-quantum key encapsulation (X-Wing and ML-KEM-768), and TLS streams gain session resumption and TLS 1.3 early data.
  • A new error_include_args INI setting includes function arguments in error messages consistently. It is off by default.

On performance, printf() calls that use only %s and %d are compiled into string interpolation, array_map() with a first-class callable or a partial application is compiled into a loop, stateless closures are cached and JSON encoding is faster.

Behaviour changes that can break code

Three session settings have new defaults, so that a plain PHP session is safer without configuration:

SettingPHP 8.5 defaultPHP 8.6 defaultWhat changes
session.use_strict_mode01Session IDs the server did not issue are rejected, which blocks session fixation
session.cookie_httponly01JavaScript can no longer read the session cookie
session.cookie_samesitenot set"Lax"The cookie is not sent on cross-site POST requests

Set the old value explicitly only if the application really depends on it, for example a payment provider that returns the customer with a cross-site POST. Other changes to test for:

  • trim(), ltrim() and rtrim() now also strip the form feed character (\f) by default.
  • fclose(), file_put_contents() and copy() return false when flushing or closing the stream fails, instead of ignoring the failure.
  • Many functions throw a ValueError where they used to truncate or ignore: file functions such as file_exists() and is_file() given a path containing a NUL byte, array_filter() with an invalid mode, pathinfo() with invalid flags.
  • preg_grep() returns false on a PCRE error instead of a partial array.
  • A by-reference foreach may now visit elements it used to skip after the array is compacted.
  • A file is treated as a Phar archive only when .phar is an extension in its file name, not when it appears in a directory name.
  • On a hard out-of-memory condition PHP calls abort(), so the exit code becomes 134 and a core dump may be written.

Deprecations in PHP 8.6

Deprecated code still runs and emits E_DEPRECATED. Fix these before the next major version removes them:

DeprecatedUse instead
return inside a finally blockReturn after the block; a return there silently discards the exception
Returning a value from __construct() or __destruct()Remove the return value
is_double(), is_long(), is_integer(), doubleval()is_float(), is_int(), floatval()
spl_object_hash(), spl_classes()spl_object_id(), ReflectionExtension::getClassNames()
The mbstring regex functions (mb_ereg(), mb_split() and the rest)preg_* functions with the u modifier
strcoll() and the SORT_LOCALE_STRING sort flagThe Collator class from the intl extension
Passing an object to array_walk(), http_build_query() or mb_convert_variables()Convert it with get_object_vars() first
SplFileObject::fgetcsv(), fputcsv(), setCsvControl(), getCsvControl()The fgetcsv() and fputcsv() functions on a file handle
mysqli::stmt_init() and mysqli::get_charset()mysqli::prepare(); mysqli::character_set_name() for the name
metaphone()A userland phonetic matching library
A third argument to define()Remove it
Session handlers without create_sid() and validateId()Implement both methods

Also deprecated: using let or is as the name of a class, function or constant, _ as a constant name, several sorting and serialisation methods of ArrayIterator, and more than 16 filters in a php://filter URL without setting filter.max_filter_count.

Should you upgrade now?

BranchActive support untilSecurity fixes until
PHP 8.3Ended 31 December 202531 December 2027
PHP 8.431 December 202631 December 2028
PHP 8.531 December 202731 December 2029
PHP 8.631 December 202831 December 2030

There is no deadline that forces a move from 8.5 this year. Start now on a test branch: run the test suite on PHP 8.6 in CI, clear the deprecations and check the session defaults. Move production once your framework, your Composer dependencies and the extensions you load all support 8.6. If you are still on PHP 8.2, the deadline is closer: its security support ends on 31 December 2026, and the PHP 8.2 end-of-life checklist covers that move.

Frequently asked questions

  • When was PHP 8.6 released and how long is it supported?

    PHP 8.6 was released on 19 November 2026. It has active support until 31 December 2028 and security fixes until 31 December 2030.

  • What is partial function application in PHP 8.6?

    It is a way to supply some arguments of a call and leave the rest for later. Writing ? for one missing argument, or ... for all remaining ones, makes PHP return a Closure instead of calling the function. The function runs when the closure is called with the missing arguments.

  • Do the new session defaults in PHP 8.6 break existing applications?

    They can, if the application uses PHP's own sessions and relied on the old defaults. Strict mode is now on, the session cookie is HttpOnly and SameSite is "Lax", so a session cookie is no longer sent on cross-site POST requests and JavaScript cannot read it. Applications whose framework sets these values itself are not affected.

  • Is mb_ereg() removed in PHP 8.6?

    No. The mbstring regular expression functions are deprecated in PHP 8.6, not removed, because the Oniguruma library they depend on is no longer maintained. They still work and emit a deprecation notice. Use the preg functions with the u modifier instead.

Sources

  1. PHP 8.6 Release Announcement — The PHP Group, 2026-11-19
  2. PHP 8.6 upgrade notes (UPGRADING) — php-src
  3. Migrating from PHP 8.5.x to PHP 8.6.x — PHP Manual
  4. RFC: Partial Function Application (v2) — PHP RFC
  5. RFC: clamp() — PHP RFC
  6. RFC: Session security defaults — PHP RFC
  7. RFC: Deprecations for PHP 8.6 — PHP RFC
  8. Supported Versions — The PHP Group

Written with substantial AI assistance. Facts checked against cited sources. Editorial policy.

New tools, once a week

One short email listing what joined the directory.

The weekly email about new tools and occasional newsletters. Unsubscribe at any time.

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.