--- title: "What's New in PHP 8.6: Partial Application, clamp(), Duration, and More" author: "DevForHelp" published: "2026-11-20T09:01:39.726Z" updated: "2026-11-20T09:01:39.726Z" url: "https://zyvop.com/what-s-new-in-php-8-6-partial-application-clamp-duration-and-more-4yxij" canonical: "https://zyvop.com/what-s-new-in-php-8-6-partial-application-clamp-duration-and-more-4yxij" tags: [] --- # What's New in PHP 8.6: Partial Application, clamp(), Duration, and More Partial application, clamp(), Time\Duration, a polling API and safer session defaults: what’s new in PHP 8.6 and what to check before you upgrade. ![Cover image]() PHP 8.6.0 shipped on **November 19, 2026**. It isn't a blockbuster like 8.0 or 8.1, but it's a very practical release: a few small features you'll use daily, some quietly important foundations (a polling API and a shared `Duration` type), safer session defaults, and a long list of deprecations to clean up before they turn into errors in a future release. This post walks through what's new, what might break, and what to do before you upgrade. > **Patch day, too.** 8.6.0 landed alongside security releases for every supported branch: **8.5.13, 8.4.28, 8.3.37 and 8.2.36**. They fix 17 CVEs, seven of them rated critical, although the project notes that the critical ones need non-default configuration or uncommon setups. Whether or not you're moving to 8.6 yet, update the branch you're on. * * * ## TL;DR | Area | Highlights | | --- | --- | | Language | Partial function application, readonly property defaults, `#[\Override]` on constants and enum cases, property writes on objects held in constants, doc comments on parameters | | New built-ins | `clamp()`, `Time\Duration`, `SortDirection` enum, `Io\Poll` polling API | | Reflection | `isReadable()` / `isWritable()`, `ReflectionParameter::getDocComment()`, namespace helpers on attributes and constants | | Runtime | Unified stream error handling, error locations in JSON messages, `error_include_args` | | Security | Stricter session defaults, post-quantum primitives and more in Sodium | | Performance | Faster `array_map()` with callable syntax, cached stateless closures, faster ZTS builds, JIT on ZTS for Apple Silicon | | Cleanup | Many deprecations (`finally` returns, `is_integer()`, `spl_object_hash()`, `mb_ereg*`, and more) | * * * ## 1\. Partial Function Application Partial function application (PFA) lets you pre-fill some arguments of a function and get back a `Closure` that accepts the rest. A `?` marks one argument to supply later, and `...` stands in for all remaining arguments. The function itself only runs once the closure is called with the missing values. ```php $zeroPad = str_pad(?, 8, '0', STR_PAD_LEFT); $isAppClass = str_starts_with(?, 'App\\'); echo $zeroPad('42'); // 00000042 $appClasses = array_filter($classNames, $isAppClass); $dashesToSpaces = str_replace('-', ' ', ...); // accepts the remaining arguments ``` The rules worth knowing, straight from the manual: - **Arguments are evaluated once, when the closure is created**, not each time it's called. - **Every** `?` **becomes a required parameter** on the closure, even if the original parameter was optional. - **Without** `...`**, extra arguments passed to the closure are ignored** rather than forwarded to the original function. That keeps optional parameters from being triggered accidentally by callers like `array_map()`. - **Named placeholders** are supported (`attempt: ?`), and the closure's parameters follow the order in which you write the placeholders, so you can reorder them. - An `ArgumentCountError` is thrown when the closure is created if the arguments and placeholders don't match the function's parameters. - Constructors can't be partially applied. PFA pairs nicely with the pipe operator from PHP 8.5, which needs each step to be a callable taking exactly one argument: ```php $slug = ' Hello PHP 8.6 ' |> trim(...) |> strtolower(...) |> str_replace(' ', '-', ?); // hello-php-8.6 ``` * * * ## 2\. `clamp()` Every codebase has a helper that keeps a number inside a range, usually written as `min(max($value, $low), $high)` and occasionally written backwards. PHP 8.6 ships it natively: ```php clamp(10, min: 0, max: 100); // 10 clamp(101, min: 0, max: 100); // 100 clamp(-5, min: 0, max: 100); // 0 $workers = clamp($requested, min: 1, max: 64); ``` It isn't limited to integers. It uses PHP's standard comparison rules, so anything comparable works, including strings, `DateTimeImmutable` objects, and the new `Duration`: ```php $start = clamp( $requestedStart, min: new DateTimeImmutable('2026-01-01'), max: new DateTimeImmutable('2026-12-31'), ); $timeout = clamp( $userTimeout, min: Time\Duration::fromSeconds(1), max: Time\Duration::fromMinutes(10), ); ``` Two behaviors worth knowing: - If `$min` is greater than `$max`, or either bound is `NAN`, `clamp()` throws a `ValueError`. Bad bounds fail loudly instead of returning nonsense. (A `NAN` _value_ just comes back as `NAN`.) - The manual warns that mixing types can give surprising results, because the usual loose-comparison rules apply. Keep the arguments the same type. **Heads-up:** `clamp()` is now a built-in global function, so a userland global function with the same name will clash with it. Many frameworks and utility packages define one, so search your code and dependencies before upgrading. * * * ## 3\. `Time\Duration` PHP 8.6 adds `Time\Duration`, a `final readonly` class for a fixed length of elapsed time, like a timeout or a stopwatch reading, with **nanosecond precision**. It has no time zone and no calendar units, which is exactly why it's not a replacement for `DateInterval`: the largest unit you can create one from is the hour, because a "day" can be 23 or 25 hours long across a DST change. ```php use Time\Duration; function retryDelay(int $attempt): Duration { $delay = Duration::fromMilliseconds(100)->multiplyBy(2 ** $attempt); return min($delay, Duration::fromSeconds(30)); // durations are comparable } $delay = retryDelay(3); time_nanosleep($delay->seconds, $delay->nanoseconds); $remaining = Duration::fromMinutes(1)->sub(Duration::fromSeconds(2, 500_000_000)); printf("%d.%09d seconds\n", $remaining->seconds, $remaining->nanoseconds); // 57.500000000 seconds ``` What the manual documents: - **Factories:** `fromHours()`, `fromMinutes()`, `fromSeconds($seconds, $nanoseconds = 0)`, `fromMilliseconds()`, `fromMicroseconds()`, `fromNanoseconds()`, and `fromIso8601DurationString()`. - **Operations:** `add()`, `sub()`, `multiplyBy()`, `divideBy()`, `negate()`, `absolute()`, and a static `compare()`. Every operation returns a new object. - **Properties:** `$seconds`, `$nanoseconds`, and `$negative`. The sign applies to the whole duration, so a negative 1.5 seconds has `seconds = 1`, `nanoseconds = 500000000`, and `negative = true`. - **Operators:** the comparison operators (`<`, `==`, `<=>` and friends) work, and so do `min()` and `max()`. The arithmetic operators do not; use the methods. - **Range:** about 292 years on 64-bit platforms (about 68 on 32-bit). Going past that throws a `Time\TimeException`. Be realistic about adoption. The one core function that accepts a `Duration` today is `Io\Poll\Context::wait()` (see section 8), and there's no `DateTime` integration yet. Functions like `sleep()` still want plain integers, which is why the example above converts back to seconds and nanoseconds for `time_nanosleep()`. The class is explicitly groundwork for a future date and time API. * * * ## 4\. Readonly Properties Can Have Defaults Until now, giving a `readonly` property a default value was a compile-time error. The original reasoning was sensible: a readonly property with a fixed default looks like a constant. Property hooks changed the picture. Since PHP 8.4, interfaces can require a get-only property, and satisfying that contract with a fixed value is perfectly reasonable: ```php interface HasName { public string $name { get; } } final class CreateUsersTable implements HasName { public readonly string $name = '2026_01_01_create_users_table'; } ``` This applies to instance properties, including those in `readonly` classes. The default counts as the property's initialization, so a constructor can't overwrite it later. * * * ## 5\. `#[\Override]` Now Covers Constants and Enum Cases `#[\Override]` arrived for methods in 8.3 and for properties in 8.5. In 8.6 it works on **class constants and enum cases** too. If the marked constant doesn't actually override one from a parent class or interface, PHP raises a fatal error, which turns typos into build failures. ```php class Base { protected const VERSION = '1.0'; } class Child extends Base { #[\Override] public const VERSION = '2.0'; // OK #[\Override] public const VERSOIN = '2.0'; // Fatal error: nothing to override } ``` * * * ## 6\. Property Writes on Objects Stored in Constants Since PHP 8.1, a global constant can hold an object created with `new`. But writing to that object's properties failed with "Cannot use temporary expression in write context". PHP 8.6 allows property writes (including compound assignment and increment), `isset()`, and `unset()` on objects referenced through constants: ```php final class Settings { public int $timeout = 10; public int $retries = 0; } const SETTINGS = new Settings(); SETTINGS->timeout = 30; // a fatal error before 8.6 SETTINGS->retries++; var_dump(SETTINGS->timeout); // int(30) ``` The constant itself is still immutable, so it always points at the same object; only the object's state changes. A few edges: - It works through global and class constants, but `new` is still only allowed in _global_ constant initializers. - Array and dimension writes through a constant remain an error. - Enum cases are class constants too, but writing to their readonly properties still fails. It now surfaces as a runtime `Error` instead of a compile-time one. * * * ## 7\. Doc Comments on Function Parameters Doc comments can now be attached directly to a parameter, and `ReflectionParameter::getDocComment()` reads them back. No more repeating a parameter's name and type in a `@param` tag above the function: ```php function search( /** Terms to look for */ string $query, /** Maximum number of results */ int $limit = 10, ): array { // ... } ``` This is mostly a win for static analyzers, IDEs, and frameworks that build documentation or schemas from reflection (API generators and AI tool definitions, for example). * * * ## 8\. The `Io\Poll` Polling API PHP's built-in tool for watching many streams at once has long been `stream_select()`, which doesn't scale gracefully (it's built on `select()`, which typically tops out around 1024 connections). PHP 8.6 adds the `Io\Poll` namespace, a unified interface over the best mechanism on each platform: **epoll** on Linux, **kqueue** on BSD and macOS, **event ports** on Solaris, **WSAPoll** on Windows, with plain `poll()` as a fallback. A small echo server shows the shape of it. Note that `StreamPollHandle` is a global class, so it isn't part of the `Io\Poll` import (in a namespaced file, write `\StreamPollHandle`): ```php use Io\Poll\{Context, Event}; use Time\Duration; $server = stream_socket_server('tcp://0.0.0.0:8080'); stream_set_blocking($server, false); $poll = new Context(); // picks the best backend automatically $poll->add(new StreamPollHandle($server), [Event::Read]); while (true) { foreach ($poll->wait(Duration::fromSeconds(1)) 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); } } } ``` `Context::wait()` takes an optional `Time\Duration` timeout (omit it to wait indefinitely) and an optional cap on the number of events. Some early articles still show integer seconds there; that was the original RFC, which was changed before release. Set expectations correctly: this is **not** a new async runtime. It's a low-level foundation that event-loop libraries such as ReactPHP and AMPHP can build on. If you write your own network code, though, it's a real upgrade over `stream_select()`. * * * ## 9\. A Shared `SortDirection` Enum Every library has invented its own way to say "ascending or descending": integers, strings, booleans, or custom enums. PHP 8.6 adds a built-in enum with `Ascending` and `Descending` cases so libraries can accept one common type in their public APIs without adapter code. It also gives you a proper type error when someone passes the wrong thing: ```php $query->orderBy('created_at', SortDirection::Descending); ``` * * * ## 10\. Enums Can Implement `__debugInfo()` Enums have always been restricted from defining most magic methods. PHP 8.6 lifts that restriction for `__debugInfo()`, so you can customize `var_dump()` output: ```php enum Status: int { case Ok = 200; case NotFound = 404; public function __debugInfo(): array { return [self::class . '::' . $this->name . ' = ' . $this->value]; } } ``` Declare the return type as `array`: a nullable `?array` return type on `__debugInfo()` is now deprecated. * * * ## 11\. Reflection Upgrades After `readonly` (8.1) and asymmetric visibility (8.4), `ReflectionProperty::isPublic()` no longer tells you whether a property can actually be written. The new `isReadable()` and `isWritable()` methods answer that for a given scope (where `null` means global scope), and optionally for a specific object. They take visibility, initialization state, hooks, and magic methods into account: ```php class Account { public function __construct( public readonly string $id, public private(set) int $balance = 0, ) {} } $account = new Account('acc_1'); $balance = new ReflectionProperty(Account::class, 'balance'); $balance->isReadable(null, $account); // true $balance->isWritable(null, $account); // false: private(set) from global scope $balance->isWritable(Account::class, $account); // true: allowed inside the class ``` There are also new `inNamespace()`, `getNamespaceName()` and `getShortName()` helpers on `ReflectionAttribute`, and `inNamespace()` on `ReflectionConstant`. * * * ## 12\. Better Streams, URIs, and Error Messages ### Unified stream error handling Streams get a consistent error model. Operations can be configured to throw a `StreamException` or to fail silently instead of emitting warnings. Errors come back as structured `StreamError` objects carrying a `StreamErrorCode` enum case, the wrapper name, and the path. You can also fetch them later with `stream_last_errors()` and clear them with `stream_clear_errors()`. ```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) { log_error($error->code->name, $error->message, $error->wrapperName); } } ``` ### URI extension follow-ups The URI extension introduced in PHP 8.5 gains builders for both standards, `Uri\Rfc3986\UriBuilder` and `Uri\WhatWg\UrlBuilder`, for assembling a URI from its components. There are also new inspection methods (`getUriType()`, `getHostType()`, `isSpecialScheme()`) and a `Uri\WhatWg\url_percent_encode()` function for encoding a string for a specific URL component. ### Errors tell you more - **JSON:** error messages from `json_last_error_msg()` and `JsonException` now include the location of the problem in the input, so you're no longer left guessing where a payload broke. - `error_include_args`**:** a new INI setting, off by default, that makes errors from built-in functions include the arguments the function received. A warning like `chmod(): Operation not permitted` becomes `chmod('/', 511): Operation not permitted`. It uses the same formatting as stack traces, so `#[\SensitiveParameter]` values are hidden and long strings are truncated at `zend.exception_string_param_max_len`. It's handy in development; think twice before enabling it in production, since arguments can still end up in your logs. * * * ## 13\. Safer Session Defaults Three `php.ini` session defaults change to be secure out of the box: | Setting | Old default | New default | | --- | --- | --- | | `session.use_strict_mode` | `0` | `1` | | `session.cookie_httponly` | `0` | `1` | | `session.cookie_samesite` | unset | `Lax` | What each one can affect, per the migration guide: - **Strict mode** rejects uninitialized session IDs, which mitigates session fixation. Custom handlers that relied on accepting externally supplied IDs must implement `validateId()` and `create_sid()`, or set this back to `0` explicitly. - **HttpOnly** hides the session cookie from JavaScript. Code that reads the session ID from `document.cookie` will stop working unless you set it back to `0`. - **SameSite=Lax** means session cookies are no longer sent on cross-site requests other than top-level navigations using safe HTTP methods. Apps that depend on cross-site `POST` submissions carrying the session need `"None"` (plus `session.cookie_secure=1`). If you maintain a **custom session handler**, there's more to check: - `session_set_save_handler()` now deprecates handlers that don't implement both `create_sid()` and `validateId()`. - `SessionHandler::validateId()` has been added, and a subclass declaring it without a return type gets a deprecation notice. - With `session.lazy_write` on, a session that is read empty and stays empty now triggers `updateTimestamp()` instead of `write()`. A handler that relied on `write()` being called with empty data (to destroy the session, for example) needs the same logic in `updateTimestamp()`. Most modern frameworks manage their own session cookies and won't notice. Apps on native PHP sessions should test. * * * ## 14\. Performance Improvements Set expectations first: Tideways' benchmarks found no measurable difference in overall application performance between 8.5 and 8.6. The gains show up in specific patterns: - `array_map()` with a first-class callable or PFA callback (for example `array_map(strtolower(...), $names)`) is compiled into the equivalent loop. - `printf()` calls are faster. - Stateless closures (static, with no captured or static variables) are cached and reused instead of being recreated on every evaluation. - `json_encode()` is faster. - Deeply recursive code that makes the VM allocate new stack pages is faster, and so is sorting single-element arrays. - **ZTS builds are faster overall, and the JIT now works on thread-safe builds on Apple Silicon**, which matters for runtimes like FrankenPHP. - The tail-call VM is now enabled on Windows when compiling with Clang 19 or later on x86\_64. - Smaller wins include faster `DOMText::splitText()`, buffered output in GD's `imagebmp()` family when writing to streams, and cheaper normalized getters on `Uri\Rfc3986\Uri`. * * * ## 15\. Other Additions - `grapheme_strrev()` reverses a string by grapheme cluster, so emoji and combining characters stay intact. - `pack()` and `unpack()` accept `<` and `>` endianness modifiers on integer and float format codes. - `mysqli::quote_string()` and `mysqli_quote_string()` escape and quote a string, similar to `PDO::quote()`. - `ZipArchive::openString()` and `closeString()` read and write zip archives in memory. - TLS streams support session resumption (new `Openssl\Session` class), external pre-shared keys (`Openssl\Psk`), and TLS 1.3 early data (0-RTT), and there's a new `stream_socket_get_crypto_status()`. - Sodium adds the **X-Wing** and **ML-KEM-768** post-quantum key encapsulation functions (when built against libsodium 1.0.22 or later), IP address encryption (`ipcrypt`), and the SHAKE and TurboSHAKE extendable-output functions. - Intl adds `IntlNumberRangeFormatter`, `Locale::getDisplayKeyword()`, `Locale::getDisplayKeywordValue()`, and more `SpoofChecker` and `IntlDatePatternGenerator` helpers. - GMP gains `gmp_powm_sec()` and `gmp_prevprime()`. - `ini_get_all()` with `$details = true` now includes each directive's built-in default. - The built-in development server accepts the HTTP `QUERY` method. - Mbstring's Unicode data tables are updated to Unicode 18.0. * * * ## 16\. Backward-Incompatible Changes The [migration guide]() has the full list. These are the ones most likely to touch application code (the session changes are covered in section 13, and the `clamp()` name clash in section 2): **Things that can bite quietly** - `trim()`, `ltrim()`, and `rtrim()` now strip the form feed character (`\f`) by default. - `fclose()`, `file_put_contents()`, and `copy()` return `false` when flushing or closing the stream fails. Those failures used to be silent. - `??` and `empty()` on a magic property no longer call `__get()` when `__isset()` has already written the property. The freshly written value is returned directly. - By-reference `foreach` loops can now visit previously skipped elements after array compaction. - `array_intersect()` converts values to strings while scanning, not during sort comparisons, which can change the number and order of conversion warnings and `__toString()` calls. - `unpack()` reads `<` or `>` right after a format code as an endianness modifier, so `s) - [Migrating from PHP 8.5.x to PHP 8.6.x (manual)]() - [Backward incompatible changes]() - [New classes and interfaces]() and [new functions]() - Manual pages: [Partial function application](), `Time\Duration`, `clamp()` - [PHP 8 ChangeLog]() - RFCs: [Partial function application](), [Duration class](), [Polling API](), [clamp()](), [Readonly property defaults](), [Object property writes on constants](), [SortDirection enum](), [Stream errors](), [Parameter doc comments](), [isReadable/isWritable](), [Function arguments in errors]() _Code samples are illustrative. Always check the manual for the exact signatures in your build._