PHP Advent

#[Language]

PHP 8.5 Features: What Changed and How to Upgrade

· 15 min read

A developer workstation at twilight with a dual-monitor setup displaying abstract code layouts, an open notebook with architecture diagrams, and a dark ceramic coffee mug.

PHP 8.5 reduces boilerplate in object-oriented code and tightens type safety. The pipe operator lets you write transformations in execution order, cloning supports property updates, and a new attribute warns when callers ignore a return value. The standard library also gets a native URI extension and simpler array lookups, while deprecations address older behaviors.

Applications already running PHP 8.3 or 8.4 generally have a straightforward upgrade to PHP 8.5. Most changes preserve backward compatibility. The exceptions mostly involve loose typing, deprecated casts, and unusual type conversions. Before adopting the new syntax, check where it fits your code and where it makes debugging harder. The examples below cover the major additions, followed by the deprecations and tests to work through before a production upgrade.

The official release details and technical specifications are in the PHP 8.5 release announcement and the PHP 8.5 migration guide.

The Pipe Operator

Nested function calls make you read an expression inside out. The first operation sits in the middle; the last wraps everything else. You can make the order clearer with intermediate variables, but sometimes those variables exist only to pass a result to the next function.

PHP 8.5 introduces the pipe operator (|>), tracked in the Pipe Operator v3 RFC. The operator evaluates left to right. It takes the expression on the left and passes its result as the single argument to the callable on the right.

Geometric glass prisms aligned in sequence on a wooden table bend flowing trails of light to illustrate step-by-step pipeline transformations.

Before and After: Data Transformation Pipelines

Consider formatting an incoming user input string into a URL slug. In PHP 8.4 and earlier, nested calls require reading from the innermost expression outwards:

<?php

$title = '  Building Clean APIs in PHP 8.5  ';

$slug = strtolower(
    str_replace(
        ' ',
        '-',
        preg_replace(
            '/[^a-z0-9 ]/i',
            '',
            trim($title)
        )
    )
);

var_dump($slug);
// string(29) "building-clean-apis-in-php-85"

In PHP 8.5, the pipe operator structures the transformation sequentially. Combined with first-class callables (trim(...), strtolower(...)), each step reads in the exact order of execution:

<?php

$rawInput = '  Building Clean APIs in PHP 8.5  ';

$slug = $rawInput
    |> trim(...)
    |> (fn(string $str): string => (string) preg_replace('/[^a-z0-9 ]/i', '', $str))
    |> (fn(string $str): string => str_replace(' ', '-', $str))
    |> strtolower(...);

var_dump($slug);
// string(29) "building-clean-apis-in-php-85"

When Not to Use the Pipe Operator

Use pipes for transformations that take a single argument. When a function needs several arguments and cannot be expressed cleanly as a first-class callable, you need an anonymous function around it. That extra syntax can make the chain harder to read than the original statements.

Avoid using the pipe operator when:

  • An operation writes to a database, emits an event, or writes log records. Separate statements with explicit error handling make these side effects easier to isolate.
  • Later operations need the same intermediate value more than once. A pipe chain passes values along in sequence; use variables when the work branches.
  • Debugging a long pipeline means inspecting values at several points. Separate statements are easier to step through with a debugger.

Clone With Property Updates

Readonly classes and immutable value objects are useful defaults in modern PHP code. Changing just one property on an immutable object, though, has required plenty of boilerplate. Custom "with" methods had to repeat constructor arguments, use reflection, or unpack the object's state.

PHP 8.5 extends clone with a function-like form that accepts an array of property updates, as specified in the Clone with v2 RFC. It clones the object and applies the new values during cloning, allowing updates that readonly property reassignment rules would otherwise prevent.

Before and After: Immutable With-er Methods

In PHP 8.4 and earlier, creating a modified copy of a readonly object required manually passing all existing properties back to the constructor:

<?php

readonly class ServiceConfiguration
{
    public function __construct(
        public string $endpoint,
        public int $timeoutMs,
        public int $retries,
        public bool $debug = false,
    ) {}

    public function withTimeout(int $timeoutMs): self
    {
        return new self(
            $this->endpoint,
            $timeoutMs,
            $this->retries,
            $this->debug,
        );
    }
}

$base = new ServiceConfiguration('https://api.internal.net', 1000, 3);
$fast = $base->withTimeout(250);

var_dump($fast->timeoutMs);
// int(250)

In PHP 8.5, the clone expression updates properties directly without restating untouched properties:

<?php

readonly class ServiceConfiguration
{
    public function __construct(
        public string $endpoint,
        public int $timeoutMs,
        public int $retries,
        public bool $debug = false,
    ) {}

    public function withTimeout(int $timeoutMs): self
    {
        return clone($this, [
            'timeoutMs' => $timeoutMs,
        ]);
    }
}

$base = new ServiceConfiguration('https://api.internal.net', 1000, 3);
$fast = $base->withTimeout(250);

var_dump($fast->timeoutMs);
// int(250)

When Not to Use Clone With

Before using clone($object, [...]) to simplify a value object, check how that object validates its state:

  • Cloning does not invoke __construct(). If your constructor enforces complex domain invariants, such as verifying cross-field relationships or validating external preconditions, those checks will not execute during a clone. Use __clone() to run required validations on cloned instances.
  • Do not use clone with on mutable entities or stateful service containers. Mutable domain models can update their properties directly without creating duplicate object allocations.
  • Avoid passing untyped or unvalidated dynamic arrays into clone(). Passing an unknown property key triggers an error, and type constraints on properties are strictly enforced.

Guarding Return Values with the NoDiscard Attribute

It is easy to lose a calculation by ignoring the return value of a pure function or immutable method. Calling $money->add($fee) on an immutable Money instance returns a new object. Forget to assign that object and the original balance stays unchanged, with no indication that you lost the result.

PHP 8.5 adds the #[\NoDiscard] attribute, implemented via the NoDiscard RFC. For a function or method with this attribute, PHP checks whether the caller uses the return value. A standalone call that neither stores nor inspects the result, nor uses it in a chain, produces an E_WARNING.

Before and After: Catching Ignored Calculations

In PHP 8.4 and earlier, forgetting to assign a returned value passed without any engine notice:

<?php

class AccountBalance
{
    public function __construct(public readonly int $cents) {}

    public function deposit(int $amount): self
    {
        return new self($this->cents + $amount);
    }
}

$balance = new AccountBalance(5000);

// The developer mistakenly assumes deposit mutates $balance in place.
$balance->deposit(1500);

var_dump($balance->cents);
// int(5000) - The deposit was silently lost.

In PHP 8.5, marking the method with #[\NoDiscard] notifies developers immediately during test runs or development:

<?php

class AccountBalance
{
    public function __construct(public readonly int $cents) {}

    #[\NoDiscard]
    public function deposit(int $amount): self
    {
        return new self($this->cents + $amount);
    }
}

$balance = new AccountBalance(5000);

// Emits Warning: The return value of method AccountBalance::deposit()
// should either be used or intentionally ignored by casting it as (void)
$balance->deposit(1500);

// Correct usage:
$balance = $balance->deposit(1500);
var_dump($balance->cents);
// int(6500)

If a caller genuinely intends to discard a return value from a #[\NoDiscard] function, PHP provides the (void) cast to explicitly silence the warning:

<?php

#[\NoDiscard]
function calculateTotal(int $subtotal, int $tax): int
{
    return $subtotal + $tax;
}

(void) calculateTotal(5000, 500);

When Not to Use NoDiscard

  • Do not apply #[\NoDiscard] to methods whose primary purpose is a side effect. For example, a repository method that saves a record and returns an optional count or status boolean should not mandate that every caller capture the return value.
  • Avoid adding #[\NoDiscard] to fluent interface methods that return $this. Callers frequently call fluent methods at the end of a chain without saving the final instance reference.
  • Do not use #[\NoDiscard] on trivial getter methods where omitting assignment carries no runtime risk other than dead code. Reserve it for safety-critical domain logic, builder methods, and validation routines.

Native URI Extension

PHP code has traditionally used parse_url(), http_build_query(), or userland packages to work with URLs. Those functions do different jobs, and building a URL by stitching strings together takes care. The new URI classes give you a consistent object API for parsing and resolving references.

PHP 8.5 introduces a built-in, always-available uri extension that adheres to RFC 3986 and WHATWG URL specifications. The accepted URI API RFC describes its two parsing models. It provides dedicated classes in the Uri namespace, primarily Uri\Rfc3986\Uri and Uri\Whatwg\Url.

Before and After: Parsing and Inspecting URLs

In PHP 8.4 and earlier, parse_url() returned an untyped associative array with nullable keys:

<?php

$urlString = 'https://admin:secret@api.example.com:8443/v1/resources?status=active#summary';

$parts = parse_url($urlString);

$host = $parts['host'] ?? null;
$port = $parts['port'] ?? null;
$user = $parts['user'] ?? null;

var_dump($host, $port, $user);
// string(15) "api.example.com"
// int(8443)
// string(5) "admin"

In PHP 8.5, the RFC 3986 URI object provides strongly typed methods, immutability, and built-in normalization:

<?php

use Uri\Rfc3986\Uri;

$urlString = 'https://admin:secret@api.example.com:8443/v1/resources?status=active#summary';

$uri = new Uri($urlString);

$host = $uri->getHost();
$port = $uri->getPort();
$user = $uri->getUserInfo();

var_dump($host, $port, $user);
// string(15) "api.example.com"
// int(8443)
// string(12) "admin:secret"

The new URI extension also supports relative URL resolution against a base URI, eliminating manual string stitching:

<?php

use Uri\Rfc3986\Uri;

$base = new Uri('https://api.example.com/v1/users/');
$resolved = new Uri('../orders/recent', $base);

var_dump((string) $resolved);
// string(40) "https://api.example.com/v1/orders/recent"

When Not to Use the URI Extension

  • For internal service identifiers or message broker routing keys that do not adhere to RFC 3986 or WHATWG URL syntax, standard string manipulation remains more suitable.
  • If a code path only needs to check a known, fixed prefix, a URI object may add complexity without helping. Measure before changing a hot path.

Native array_first and array_last Functions

Getting the first or last value from an array has required some care. Both reset() and end() change the internal pointer and take the array by reference. You can use $array[array_key_first($array)] instead, but it takes more code, and you must check for an empty array to avoid notices.

PHP 8.5 introduces array_first() and array_last() directly in core, as specified by the accepted array boundary functions RFC. Both functions accept an array and return the first or last value without touching internal pointers. If the array is empty, both functions return null.

Before and After: Retrieving Boundary Values

In PHP 8.4 and earlier, safely grabbing the last element without modifying pointers required multiple operations:

<?php

$revisions = ['v1.0.0', 'v1.1.0', 'v1.2.0'];

$latest = $revisions === []
    ? null
    : $revisions[array_key_last($revisions)];

var_dump($latest);
// string(6) "v1.2.0"

In PHP 8.5, the helper function simplifies the lookup to a single call:

<?php

$revisions = ['v1.0.0', 'v1.1.0', 'v1.2.0'];

$latest = array_last($revisions);

var_dump($latest);
// string(6) "v1.2.0"

Because both functions return null on an empty array, they chain cleanly with the null coalescing operator:

<?php

$emptyQueue = [];

$firstJob = array_first($emptyQueue) ?? 'default-task';

var_dump($firstJob);
// string(12) "default-task"

When Not to Use array_first and array_last

  • If your array contains null values as valid data, array_first() returning null does not tell you whether the array was empty or whether its first item was explicitly null. Use array_key_first($array) !== null when you must distinguish between empty arrays and arrays containing nulls.
  • These functions operate specifically on native PHP arrays. They do not accept general Traversable objects, iterators, or generators.

Closures and First-Class Callables in Constant Expressions

Recent PHP releases have expanded constant expressions to allow scalar expressions, array literals, and object instantiation with new. Callables were still excluded: you could not pass one as an attribute argument or use one as a parameter default or class constant.

PHP 8.5 allows static closures and first-class callables within constant expressions. The closures in constant expressions RFC covers the restrictions. You can use them to declare callable behavior in framework attributes, configuration classes, and validation rules.

Before and After: Attribute Callables

In PHP 8.4 and earlier, attributes requiring callable logic had to rely on strings containing class and method names, or instantiate dedicated expression wrapper objects:

<?php

#[\Attribute(\Attribute::TARGET_METHOD)]
class RouteGuard
{
    public function __construct(public string $checkerClass, public string $checkerMethod) {}
}

class InvoiceSecurity
{
    public static function canView(int $id): bool { return $id >= 1; }
}

class InvoiceController
{
    #[RouteGuard(InvoiceSecurity::class, 'canView')]
    public function show(int $id): void {}
}

In PHP 8.5, first-class callables and static closures can be supplied directly in the attribute declaration:

<?php

#[\Attribute(\Attribute::TARGET_METHOD)]
class RouteGuard
{
    /** @var callable */
    public $checker;

    public function __construct(callable $checker)
    {
        $this->checker = $checker;
    }
}

class InvoiceSecurity
{
    public static function canView(int $id): bool { return $id > 0; }
}

class InvoiceController
{
    #[RouteGuard(InvoiceSecurity::canView(...))]
    public function show(int $id): void {}
}

Static closures can also encapsulate inline evaluation rules directly inside attribute arguments:

<?php

#[\Attribute(\Attribute::TARGET_PROPERTY)]
class ValidateWith
{
    /** @var callable */
    public $rule;

    public function __construct(callable $rule)
    {
        $this->rule = $rule;
    }
}

class UserRegistration
{
    #[ValidateWith(static fn(string $val): bool => strlen($val) >= 8)]
    public string $password;
}

When Not to Use Callables in Constant Expressions

  • Constant expressions cannot bind $this or access non-static external scope. Closures defined in constant expressions must remain static.
  • Placing large closures or non-trivial business logic inside attribute arguments decreases readability. Keep attribute callables concise or delegate to named static methods.

Persistent cURL Share Handles

An application that talks to external microservices or third-party APIs may make dozens of HTTP requests while handling a request. With PHP-FPM, each incoming web request starts fresh. Standard cURL share handles (curl_share_init()) let several cURL handles share DNS caches and connection pools during one PHP request, but those resources were destroyed when that request ended.

PHP 8.5 introduces curl_share_init_persistent(), described in the persistent cURL share RFC. This function creates or reuses a persistent share handle that survives across multiple requests within the same long-lived worker process. Reusing DNS lookups and connections may save setup work on later requests; measure the effect in your application.

Before and After: Reusing cURL Connections

In PHP 8.4 and earlier, cURL share handles were created and destroyed on every request:

<?php

$shareHandle = curl_share_init();
curl_share_setopt($shareHandle, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt($shareHandle, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);

$ch = curl_init('https://example.com/');
curl_setopt($ch, CURLOPT_SHARE, $shareHandle);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
// When the script ends, connection pools and DNS caches are destroyed.

In PHP 8.5, persistent share handles retain connection state across subsequent requests handled by the worker:

<?php

// Reuses an existing handle matching these share options if one exists in the worker.
$shareHandle = curl_share_init_persistent([
    CURL_LOCK_DATA_DNS,
    CURL_LOCK_DATA_CONNECT,
]);

$ch = curl_init('https://example.com/');
curl_setopt($ch, CURLOPT_SHARE, $shareHandle);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
// Sockets and DNS resolutions remain cached for subsequent requests.

When Not to Use Persistent cURL Shares

  • In single-execution CLI scripts or isolated background jobs, persistent share handles offer no latency benefit over standard handles.
  • Do not try to share cookies between requests: CURL_LOCK_DATA_COOKIE is rejected by curl_share_init_persistent(). Review how connections are isolated if different tenants use the same worker pool.

Deprecations and Backward-Incompatible Changes

Review deprecations and breaking changes before upgrading. The complete list of deprecation notices is in the PHP 8.5 deprecations RFC and detailed in the PHP 8.5 migration guide.

Core Deprecations

The following patterns emit E_DEPRECATED notices in PHP 8.5:

  • The Backtick Operator: Executing shell commands using backticks (` $output = git rev-parse HEAD; ) is deprecated. Replace backticks with explicit shell_exec()` calls.
  • Non-Canonical Cast Names: Scalar casts using non-canonical names are deprecated. Code must use (bool), (int), (float), and (string) rather than (boolean), (integer), (double), and (binary).
  • Semicolon-Terminated Case Statements: Terminating a case condition in a switch statement with a semicolon (case 'active';) is deprecated. Use the standard colon (case 'active':).
  • Null as an Array Offset: Passing null as an array key or into array_key_exists() emits a deprecation notice. In previous versions, null silently converted to an empty string "". Update array lookups to pass empty strings explicitly or guard against null.
  • **__sleep() and __wakeup() Magic Methods:** The legacy serialization magic methods __sleep() and __wakeup() are soft-deprecated in favor of __serialize() and __unserialize().
  • Incrementing Non-Numeric Strings: Incrementing arbitrary strings using the ++ operator is deprecated. Use string manipulation functions or dedicated formatting instead.

Backward-Incompatible Changes

Inspect your application for these breaking behaviors before deploying PHP 8.5:

  • **Removal of disable_classes INI Setting:** The disable_classes configuration directive has been removed from the engine. It created unstable assumptions across internal class structures and is no longer supported.
  • Destructuring Non-Array Values: Attempting to destructure non-array values other than null using [] or list() now emits a warning.
  • Float to Int Conversion Warnings: Casting non-representable floats (or string floats that overflow integer limits) to int now emits a warning about potential data loss.
  • Restricted Class Aliases: The strings "array" and "callable" can no longer be used as alias names in class_alias().

How to Test and Execute an Upgrade

Test the upgrade before deploying it to production. Otherwise, unexpected deprecation notices can flood your logs, and unhandled warnings can break API contracts. Static analysis with PHPStan, automated tests, and staging traffic each give you a chance to find problems before users encounter them.

Step 1: Run Static Analysis on PHP 8.5 Rules

Static analysis can find type and API problems that a test suite may miss. Configure your analyzer for PHP 8.5, then search separately for deprecated syntax such as backticks, non-canonical casts, and semicolon-terminated case labels. Do not assume the analyzer flags every new engine deprecation.

Update your PHPStan or Psalm configuration to analyze against PHP 8.5:

# phpstan.neon
parameters:
    phpVersion: 80500
    level: 8
    paths:
        - src
        - tests

Run static analysis across the entire project repository:

vendor/bin/phpstan analyse --memory-limit=1G

Review the reported errors and inspect the deprecation search results by hand. Make a small change at a time and rerun the analysis; a mechanical syntax replacement can alter behavior if the surrounding code relies on it.

Step 2: Execute the Automated Test Suite

Run the full automated test suite in an isolated PHP 8.5 environment. Install the same optional extensions and configuration as production; the base php:8.5-cli image alone does not supply every extension an application may need.

A sleek laptop on a wooden desk displays glowing test suite progress bars and verification badges beside studio headphones and an espresso cup.

Greg Beaver covered test-driven verification in the PHP Advent article Testing with PHPT and xUnit. Configure PHPUnit to treat deprecations and unexpected warnings as test failures while testing the upgrade:

<!-- phpunit.xml -->
<phpunit
    failOnDeprecation="true"
    failOnNotice="true"
    failOnWarning="true"
    colors="true">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Execute tests inside a PHP 8.5 container:

docker run --rm -v $(pwd):/app -w /app php:8.5-cli vendor/bin/phpunit

Step 3: Monitor Deprecation Logs in Staging

Even a thorough test suite can miss rarely used code or unusual integrations. Configure staging to log deprecations without interrupting HTTP responses.

As Samer Atiani discussed in Merry Error Handling, capturing runtime diagnostics early prevents unhandled errors in production. Enable full error logging in staging:

; php.ini in staging
error_reporting = E_ALL
display_errors = Off
log_errors = On
error_log = /var/log/php/deprecations.log

Run normal user workflows in staging and check the deprecation log for third-party packages that need updates. Compare critical endpoints before and after the runtime change to catch execution or memory regressions.

Common Upgrade Mistakes

Avoid these frequent pitfalls when migrating applications to PHP 8.5:

An open engineering notebook shows hand-drawn flowchart pathways with crossed-out mistake branches on a dark desk in front of a diagnostics monitor.
  • Ignoring Warnings from Discarded Values: Adding #[\NoDiscard] to an existing library method can produce E_WARNING notices for downstream callers that discard its result. Start with methods at domain boundaries where you intend to require callers to use the return value.
  • Overlooking Third-Party Dependencies: Check your lockfile and package PHP constraints, then run composer check-platform-reqs in the PHP 8.5 test environment. Verify that required extensions are installed before attributing a test failure to the language upgrade.

When you hand off the migration, share the checks above with the team and record which ones passed in the PHP 8.5 environment. If a commercial package's vendor has not confirmed PHP 8.5 support yet, a short status update email that names the version and the failing check is easier to answer than a vague "any news?".