Click any bullet to expand the example I wrote while reading the release notes.
// My use-case: build a reusable log filter without wrapping in a closure $logs = [ ['level' => 'error', 'msg' => 'DB timeout'], ['level' => 'info', 'msg' => 'User login'], ['level' => 'error', 'msg' => 'API 500'], ['level' => 'warning', 'msg' => 'Low disk'], ]; // Old way: full closure every time $onlyErrorsOld = array_filter($logs, fn($l) => $l['level'] === 'error'); // PHP 8.6: pre-fill $level, leave $log as placeholder $onlyErrors = array_filter($logs, level_filter('error', ?)); // Reuse for any level – the placeholder becomes the log entry $onlyWarnings = array_filter($logs, level_filter('warning', ?)); function level_filter(string $expected, array $log): bool { return $log['level'] === $expected; } // Result: Closure(1) – no manual `use` clauses, no boilerplate
// I replaced my custom RetryHelper with Duration + partial application use Time\Duration; function retryAfter( Duration $initial, Duration $max, Duration $multiplier, int $attempt, callable $operation, ): mixed { while (true) { try { return $operation(); } catch (Throwable $e) { $wait = $initial->multiplyBy(2 ** $attempt); $wait = min($wait, $max); // durations are comparable time_nanosleep($wait->seconds, $wait->nanoseconds); $attempt++; } } } // Pre-configure: 200ms start, 10s cap, double each time $withRetry = retryAfter( Duration::fromMilliseconds(200), Duration::fromSeconds(10), Duration::fromFloat(2.0), attempt: 0, operation: ?, ); // Call with just the risky operation – duration math stays in one place $withRetry(fn() => fetchRemoteConfig());
// I've been avoiding stream_select() for years – this fixes the 1024 limit use Io\Poll\{Context, Event, StreamPollHandle}; $server = stream_socket_server('tcp://0.0.0.0:8080'); $ctx = new Context(); $ctx->add(new StreamPollHandle($server), [Event::Read]); $clients = []; while (true) { foreach ($ctx->wait() as $watcher) { $handle = $watcher->getHandle(); $stream = $handle->getStream(); if ($stream === $server) { $client = stream_socket_accept($server); $ctx->add(new StreamPollHandle($client), [Event::Read]); $clients[] = $client; continue; } $data = fread($stream, 8192); if ($data === '' || $data === false) { $watcher->remove(); fclose($stream); } else { fwrite($stream, $data); } } }
// I used max(0, min($x, 100)) at least 30 times last year. Never again. function setVolume(int $vol): int { return clamp($vol, 0, 100); } setVolume(-5); // 0 (was 0 with old max/min trick) setVolume(50); // 50 setVolume(130); // 100 // Works with any comparable, including my Duration example above $timeout = clamp( \Time\Duration::fromSeconds(90), min: \Time\Duration::fromMinutes(1), max: \Time\Duration::fromMinutes(5), ); // $timeout->seconds === 90 // Handy for pagination too $page = clamp((int) ($_GET['page'] ?? 1), 1, $totalPages);
// I got so tired of libraries accepting int $direction = 0/1 class MyQueryBuilder { 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 = new MyQueryBuilder(); $qb->orderBy('created_at', SortDirection::Descending); $qb->orderBy('name', SortDirection::Ascending); // Passing an int now fails immediately with a TypeError — // not an UnhandledMatchError deep inside the method
// My rule classes no longer need an empty constructor interface ValidationRule { public string $parser { get; } } final readonly class EmailRule implements ValidationRule { public string $parser = EmailParser::class; } final readonly class PhoneRule implements ValidationRule { public string $parser = PhoneParser::class; } // Previously each one needed: // public function __construct() { // $this->parser = EmailParser::class; // } // Now the default counts as initialization — constructor can't overwrite it
// I finally stopped duplicating $query and $limit in the @param tag class SearchService { /** * Returns matching items for the given filters. */ public function find( /** Raw search terms entered by the user */ string $query, /** Max results (1–500, clamped) */ int $limit = 25, /** Include soft-deleted records? */ bool $withTrashed = false, ): array { $limit = clamp($limit, 1, 500); return []; } } // Reflection can read each parameter's own DocComment $param = new ReflectionParameter([SearchService::class, 'find'], 'limit'); var_dump($param->getDocComment()); // string(33) "/** Max results (1–500, clamped) */"
// With asymmetric visibility, "public" isn't enough — I need real answers class Article { public string $title = 'PHP 8.6 is here'; public private(set) string $slug = 'php-86-is-here'; public string $meta = ''; public function __get($name) { return $name === 'computed' ? 'magic' : null; } } $article = new Article(); // My admin panel checks: can this user actually write this property? foreach (['title', 'slug'] as $name) { $prop = new ReflectionProperty(Article::class, $name); printf( "%-8s readable=%s writable=%s\n", $name, $prop->isReadable(null, $article) ? 'yes' : 'no', $prop->isWritable(null, $article) ? 'yes' : 'no', ); } // title: readable=yes writable=yes // slug: readable=yes writable=no ← asymmetric private(set)
// My config loader used to be a mess of @ and error_get_last() use StreamErrorMode; $ctx = stream_context_create([ 'stream' => [ 'error_mode' => StreamErrorMode::Exception, ], ]); try { $raw = file_get_contents( 'https://config.internal/app.json', context: $ctx, ); $config = json_decode($raw, true, flags: JSON_THROW_ON_ERROR); } catch (StreamException $e) { // Structured errors: enum case, wrapper name, path/URL foreach ($e->getErrors() as $err) { error_log(sprintf( '[%s] %s (%s: %s)', $err->code->name, // StreamErrorCode enum case $err->message, $err->wrapperName, $err->path ?? '?', )); } // Fallback: load last known good config $config = require '/etc/app/config.fallback.php'; } // You can also inspect errors later without try/catch: $errors = stream_last_errors();
// #[\Override] now works on class constants & enum cases too // Enums can implement __debugInfo() // Modify properties of objects stored in constants directly Config::DEFAULTS->timeout = 30; // New URI builders: Uri\Rfc3986\UriBuilder, Uri\WhatWg\UrlBuilder // + detection of URI/host types + Uri\WhatWg\url_percent_encode() $builder = new Uri\Rfc3986\UriBuilder(); $builder->setScheme('https')->setHost('example.com'); // Sodium: post-quantum KEM (X-Wing, ML-KEM-768), IP encryption, SHAKE/TurboSHAKE // TLS: session resumption, external pre-shared keys, TLS 1.3 early data (0-RTT) // mysqli::quote_string() – escape + quote, same as PDO::quote() $safe = $mysqli->quote_string($userInput); // pack()/unpack(): < and > endianness modifiers on int & float codes // JSON error messages now include the location of the error // New INI: error_include_args — consistently includes function args in errors // grapheme_strrev() – reverses by grapheme cluster (emoji-safe) grapheme_strrev("👨👩👧👦 hello"); // IntlNumberRangeFormatter – formats ranges of numbers // ZipArchive::openString() / closeString() – in-memory archives // Performance: array_map() with FCC/partial application compiled to loops // faster printf(), cached stateless closures, faster JSON encoding
// ⚠️ Every deprecation / BC break from the 8.6 notes — I've kept them all here // ── language / control flow ────────────────────────────── // return inside finally block — deprecated (silently discards exceptions) // returning a value from __construct()/__destruct() — deprecated // __construct/__destruct as generators — deprecated // nullable return type for __debugInfo() — deprecated // ── reserved / renamed identifiers ─────────────────────── // let / is as class, function, or constant name — deprecated // _ as a constant name — deprecated // namespace as a class constant name — deprecated // readonly as a function name — deprecated // ── mbstring regex ──────────────────────────────────────── // mb_ereg() / mb_split() and friends — deprecated (Oniguruma unmaintained) // use PCRE functions with the /u modifier instead // ── aliases & helpers ───────────────────────────────────── // is_double(), is_long(), is_integer(), doubleval() — deprecated // use is_float(), is_int(), floatval() instead // spl_object_hash() — deprecated (use spl_object_id()) // spl_classes() — deprecated (use ReflectionExtension::getClassNames()) // ── sorting / locale ────────────────────────────────────── // strcoll() — deprecated // SORT_LOCALE_STRING sort flag — deprecated // use Collator from the intl extension instead // ── arrays & objects ────────────────────────────────────── // passing an object where array expected to: array_walk(), array_walk_recursive(), // http_build_query(), mb_convert_variables(), compression functions/filters — deprecated // use get_object_vars() to convert first // ── define / is_a / is_subclass_of ───────────────────────── // passing a 3rd argument to define() — deprecated // is_a() / is_subclass_of() with class-name string when $allow_string=false — deprecated // ── php://filter ─────────────────────────────────────────── // >16 filters without filter.max_filter_count context option — deprecated // ── sessions ──────────────────────────────────────────────── // session.use_strict_mode and session.cookie_httponly now enabled by default // session.cookie_samesite = Lax by default // custom handlers missing create_sid() and validateId() — deprecated // ── other deprecated functions / methods ──────────────────── // metaphone(), mysqli_get_charset(), mysqli_stmt_init() — deprecated // SplFileObject CSV methods — deprecated // ArrayIterator sorting, flag & serialization methods — deprecated // ── behaviour changes (not just deprecations) ─────────────── // trim(), ltrim(), rtrim() now also strip form feed (\f) by default // fclose(), file_put_contents(), copy() return false on flush/close failure // many functions now throw ValueError for out-of-range values, // invalid flags, or strings containing NUL bytes (instead of truncating/ignoring)
PHP 8.6 · released 19 November 2026 · my personal snippets, shared as-is