
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, |
New built-ins |
|
Reflection |
|
Runtime | Unified stream error handling, error locations in JSON messages, |
Security | Stricter session defaults, post-quantum primitives and more in Sodium |
Performance | Faster |
Cleanup | Many deprecations ( |
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.
$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 argumentsThe 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 likearray_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
ArgumentCountErroris 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:
$slug = ' Hello PHP 8.6 '
|> trim(...)
|> strtolower(...)
|> str_replace(' ', '-', ?);
// hello-php-8.62. 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:
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:
$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
$minis greater than$max, or either bound isNAN,clamp()throws aValueError. Bad bounds fail loudly instead of returning nonsense. (ANANvalue just comes back asNAN.)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.
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 secondsWhat the manual documents:
Factories:
fromHours(),fromMinutes(),fromSeconds($seconds, $nanoseconds = 0),fromMilliseconds(),fromMicroseconds(),fromNanoseconds(), andfromIso8601DurationString().Operations:
add(),sub(),multiplyBy(),divideBy(),negate(),absolute(), and a staticcompare(). Every operation returns a new object.Properties:
$seconds,$nanoseconds, and$negative. The sign applies to the whole duration, so a negative 1.5 seconds hasseconds = 1,nanoseconds = 500000000, andnegative = true.Operators: the comparison operators (
<,==,<=>and friends) work, and so domin()andmax(). 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:
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.
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:
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
newis 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
Errorinstead 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:
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):
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:
$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:
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:
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 classThere 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().
$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()andJsonExceptionnow 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 likechmod(): Operation not permittedbecomeschmod('/', 511): Operation not permitted. It uses the same formatting as stack traces, so#[\SensitiveParameter]values are hidden and long strings are truncated atzend.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 |
|---|---|---|
|
|
|
|
|
|
| unset |
|
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()andcreate_sid(), or set this back to0explicitly.HttpOnly hides the session cookie from JavaScript. Code that reads the session ID from
document.cookiewill stop working unless you set it back to0.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
POSTsubmissions carrying the session need"None"(plussession.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 bothcreate_sid()andvalidateId().SessionHandler::validateId()has been added, and a subclass declaring it without a return type gets a deprecation notice.With
session.lazy_writeon, a session that is read empty and stays empty now triggersupdateTimestamp()instead ofwrite(). A handler that relied onwrite()being called with empty data (to destroy the session, for example) needs the same logic inupdateTimestamp().
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 examplearray_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'simagebmp()family when writing to streams, and cheaper normalized getters onUri\Rfc3986\Uri.
15. Other Additions
grapheme_strrev()reverses a string by grapheme cluster, so emoji and combining characters stay intact.pack()andunpack()accept<and>endianness modifiers on integer and float format codes.mysqli::quote_string()andmysqli_quote_string()escape and quote a string, similar toPDO::quote().ZipArchive::openString()andcloseString()read and write zip archives in memory.TLS streams support session resumption (new
Openssl\Sessionclass), external pre-shared keys (Openssl\Psk), and TLS 1.3 early data (0-RTT), and there's a newstream_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 moreSpoofCheckerandIntlDatePatternGeneratorhelpers.GMP gains
gmp_powm_sec()andgmp_prevprime().ini_get_all()with$details = truenow includes each directive's built-in default.The built-in development server accepts the HTTP
QUERYmethod.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(), andrtrim()now strip the form feed character (\f) by default.fclose(),file_put_contents(), andcopy()returnfalsewhen flushing or closing the stream fails. Those failures used to be silent.??andempty()on a magic property no longer call__get()when__isset()has already written the property. The freshly written value is returned directly.By-reference
foreachloops 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, sos<valuenow yields the keyvalue, not<value.session_encode()returns an empty string, notfalse, for an empty session.preg_grep()returnsfalseon a PCRE error instead of a partial array.base_convert(),bindec(),hexdec()andoctdec()raise a notice when they can't convert a number precisely.SplFileObject::fgets()no longer caches its line forcurrent(), andnext()now advances the stream when nothing is cached.A hard out-of-memory condition now calls
abort()instead ofexit(1), so the exit code becomes 134 and a core dump is possible.
Things that now throw
Many functions raise a
ValueErrorfor invalid flags, out-of-range values, or strings containing NUL bytes, includinggetenv(),putenv(),setlocale(),parse_str(),stat(),file_exists(),sleep(),usleep(), andnumber_format().ftp_nb_*calls throw anErrorwhen the connection is already transferring.Several GMP, GD, Zip, Zlib and SOAP functions are stricter about argument types and ranges.
17. Deprecations to Fix Now
Deprecations don't break anything today, but they'll surface as notices in your logs and CI.
Language
Returning from a
finallyblock, which silently discards exceptions and overrides values fromtryorcatch.Returning a value from
__construct()or__destruct(), or making either a generator. A barereturn;is still fine.Using
letorisas a class, function, or constant name, and_as a constant name. These are reserved for future syntax. Functions named_, including gettext's alias, aren't affected.Using
namespaceas a class constant name, and naming a functionreadonly.
Functions and aliases
is_double(),is_integer(),is_long(), anddoubleval(). Useis_float(),is_int(), andfloatval().spl_object_hash(). Usespl_object_id(). Andspl_classes(); useReflectionExtension::getClassNames().strcoll()and theSORT_LOCALE_STRINGflag. Use theCollatorclass.The third argument of
define(). Passingfalseis deprecated, and passingtruealready warns, with the message now saying it becomes an error in PHP 9.0.metaphone(),mysqli_get_charset()(andmysqli::get_charset()),mysqli_stmt_init(), and constructingmysqli_stmtwithout a query.Passing a string to
is_a()oris_subclass_of()when$allow_stringisfalse.Passing objects to
array_walk(),array_walk_recursive(),http_build_query(),mb_convert_variables(), and the compression functions and filters. Callget_object_vars()first.More than 16 filters in a
php://filterURL, unless you raise the newfilter.max_filter_countcontext option.
Classes and extensions
The
mb_ereg*functions andmb_split(), because the Oniguruma library is no longer maintained. They'll be removed in PHP 9.0. Use PCRE with theumodifier instead.The flag, sorting, and serialization methods
ArrayIteratorinherits fromArrayObject, and the CSV methods onSplFileObject.ReflectionProperty::setValue()andsetRawValue()with an object that isn't an instance of the declaring class, and passing an object toReflectionMethod::invoke()orinvokeArgs()for a static method (passnull).
Upgrade Checklist
Run your test suite on PHP 8.5 with
error_reporting = E_ALLand fix every deprecation notice you can see.Search for a global
clamp()function in your code and dependencies. Rename it, namespace it, or guard it withfunction_exists().Search for patterns on their way out:
is_integer(,is_long(,is_double(,doubleval(,spl_object_hash(,mb_ereg,define(with three arguments, andreturninsidefinallyblocks. Most fixes are mechanical.Test session behavior if you don't rely on a framework's session layer, and review any custom session handler (section 13).
Re-test the quiet behavior changes in section 16, especially
trim()with form feeds, ignored return values fromfclose(),file_put_contents()andcopy(), and magic__isset()/__get()code used with??.Confirm library support. Check that your framework, static analyzer, and key dependencies list PHP 8.6 compatibility before deploying to production.
Try the new toys in a branch: swap
min(max())forclamp(), passDurationvalues where you juggle seconds and milliseconds, and let PFA tidy up your pipe chains.
Final Thoughts
None of this will headline a conference keynote, and that's fine: the best parts of 8.6 are the ones that quietly delete boilerplate and give libraries shared building blocks to standardize on. If you're on PHP 8.5, expect a comfortable upgrade. If you're still on 8.2, remember that it reaches end of life on December 31, 2026, so now is the time to plan the jump.
Sources and Further Reading
Manual pages: Partial function application,
Time\Duration,clamp()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.
Comments(0)
Join the discussion by logging into your account.
No comments yet. Be the first to comment!