Skip to content
Home SE
Software

PHP 8.5 In Depth: New Features, Code Examples and a Developer Guide

Sinan Eldem

• 12 min read

PHP 8.5 In Depth: New Features, Code Examples and a Developer Guide

Key Features

The headline features of PHP 8.5 are:

  • URI Extension

  • Pipe Operator (|>)

  • Clone With – modifying properties while cloning

  • The #[\NoDiscard] Attribute

  • Closures and first-class callables in constant expressions

  • Persistent cURL Share Handles

Let's go through them one by one.

1. URI Extension

PHP 8.5 adds an “always available” URI extension to the standard library. It lets you work with URIs/URLs in compliance with both the RFC 3986 and WHATWG URL standards.

Why does it matter?

In earlier versions, parse_url() was the usual go-to for URL/URI handling, but it has limitations and has long been criticized for not being standards-compliant. The new extension offers a safer, more standards-compliant, class-based (object-oriented) API.

<?php
use Uri\Rfc3986\Uri;

$uri = new Uri('https://www.example.com:443/path/to/page?query=123#fragment');

// Host bilgisini al
echo $uri->getHost();
// Örnek çıktı: example.com

// Varsayılan port değeri varsa kaldır
if ($uri->getPort() === 443 && $uri->getScheme() === 'https') {
    $uri = $uri->withPort(null);
}

// Yeni URI’yi metin halinde al
echo $uri->toString();
// Örnek çıktı: https://www.example.com/path/to/page?query=123#fragment
?>

In the code above, the Uri\Rfc3986\Uri class is used to break a URL into its parts, check the port and modify the URI when needed.

Things to Keep in Mind

  • The extension provides not only the Uri\Rfc3986\Uri class but also classes such as Uri\WhatWg\Url that follow browser-oriented (WHATWG) standards.

  • When migrating your code, it makes sense to consider these new classes wherever you used parse_url() before.

  • The design favors immutable URI objects: you use withXxx()-style methods to make changes to a URI.

2. Pipe Operator (|>)

One of the most notable syntax additions in PHP 8.5 is the pipe operator. With the |> operator, a value can be passed from left to right through a series of callables, one after another — like a pipeline.

What is it for?

Normally you would have to nest many function calls or assign intermediate variables, and the code could become hard to read. With the pipe operator:

  • Code reads left to right (the flow of operations is clearer)

  • There are fewer intermediate variables and deeply nested function calls

  • Function chains can be written more simply

Example

First, the classic style:

<?php
$title = ' PHP 8.5 Released ';
$slug = strtolower(
    str_replace('.', '',
        str_replace(' ', '-',
            trim($title)
        )
    )
);
echo $slug;
// Çıktı: php-85-released
?>

Using the pipe operator in PHP 8.5:

<?php
$title = ' PHP 8.5 Released ';
$slug = $title
    |> trim(...)
    |> (fn($str) => str_replace(' ', '-', $str))
    |> (fn($str) => str_replace('.', '', $str))
    |> strtolower(...);

echo $slug;
// Çıktı: php-85-released
?>

In the example above, the value is processed step by step with the |> operator: first trim, then str_replace, then strtolower… It's easier to read and follow.

Limitations & Notes

  • Callables used with the pipe operator must take a single parameter. In other words, the callable on the right must accept the value coming from the left as its first parameter.

  • It may not work with functions that take parameters by reference — for example array_pop(&$array).

  • Operator precedence matters: it comes after arithmetic operators and before comparisons (==, ===). You may need parentheses to make things explicit.

3. Clone With – Updating Properties While Cloning

PHP 8.5 makes it possible to update properties while cloning an object. That means when you clone an object (the “with-er” pattern), you can create a new object with some properties changed.

Why?

When working with readonly classes, or immutable objects in general, “continuing with a new object when only a few properties change” is a common pattern. In earlier versions this usually had to be done by hand. Now the language supports it directly.

Example

<?php
readonly class Color
{
    public function __construct(
        public int $red,
        public int $green,
        public int $blue,
        public int $alpha = 255,
    ) {}
}

$blue = new Color(79, 91, 147);

// Önceki sürümde “withAlpha” benzeri yardımcı metod:
$transparentBlue = new Color(
    $blue->red,
    $blue->green,
    $blue->blue,
    128
);

// PHP 8.5 ile:
$transparentBlue2 = clone($blue, ['alpha' => 128]);

// Kullanımı:
var_dump($transparentBlue2->alpha);  // 128
?>

In the example above, the clone($object, ['alpha' => 128]) syntax creates a new object with only the alpha property changed.

Things to Watch Out For

  • This feature applies only during cloning (“clone”); it differs from the classic clone $object usage.

  • Keep supported class types and property accessibility (visibility, readonly, etc.) in mind.

  • This pattern is very handy when working with immutable objects.

4. The #[\NoDiscard] Attribute

PHP 8.5 introduces the #[\NoDiscard] attribute, which emits a warning when the return value of a function or method is left unused.

Why?

In some APIs, ignoring a function's return value can indicate a bug (for example, an operation that returns a result which is then ignored). With this attribute, you get a warning when you forget to use the return value — which improves API safety and code quality.

Example

<?php
#[\NoDiscard]
function getPhpVersion(): string
{
    return 'PHP 8.5';
}

// Kullanımı:
getPhpVersion();  
// Uyarı: getPhpVersion() fonksiyonunun döndürdüğü değer kullanılmalı ya da (void) ile kast edilmeli

// Kullanım doğru biçimde:
$version = getPhpVersion();
echo $version;

// Ya da dönüş değeri bilinçli olarak kullanılmayacaksa:
(void) getPhpVersion();
?>

In the code above, because getPhpVersion() is marked with #[\NoDiscard], calling it without using the result triggers a warning. This way, important return values don't slip through the cracks.

Things to Watch Out For

  • If a return value is intentionally unused, you can cast it with (void); this suppresses the warning.

  • This attribute should be used alongside static analysis tools (such as PHPStan and Psalm), with the goal of never overlooking return values anywhere in the code.

5. Closures and First-Class Callables in Constant Expressions

Starting with PHP 8.5, static closures and first-class callables can be used in constant expressions.

What does that mean?

  • Previously, only certain (“primitive”-like) values could be used in constants (const) or attribute parameters.

  • Now closures and callable references can also appear in constant expressions, which benefits advanced metaprogramming, attribute usage and configuration-driven solutions.

Example

<?php
final class PostsController
{
    #[AccessControl(static function (
        Request $request,
        Post $post,
    ): bool {
        return $request->user === $post->getAuthor();
    })]
    public function update(
        Request $request,
        Post $post,
    ): Response {
        // ...
    }
}
?>

In the example above, a static closure is passed as an attribute parameter — this kind of usage is now valid in constant expressions as of PHP 8.5.

Things to Watch Out For

  • This feature is especially useful for attribute-based libraries and libraries that do metaprogramming.

  • Using closures in constant expressions may require care for readability; overuse can make code more complex.

6. Persistent cURL Share Handles

PHP 8.5 supports cURL “share handles” that can be shared across multiple requests. This gives a performance boost, especially in high-traffic applications, by avoiding repeatedly opening connections to the same host.

Example

<?php
// PHP 8.4 ve öncesinde:
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);

$ch = curl_init('https://php.net/');
curl_setopt($ch, CURLOPT_SHARE, $sh);

curl_exec($ch);

// PHP 8.5 ile:
$sh = curl_share_init_persistent([
    CURL_LOCK_DATA_DNS,
    CURL_LOCK_DATA_CONNECT,
]);

$ch = curl_init('https://php.net/');
curl_setopt($ch, CURLOPT_SHARE, $sh);

curl_exec($ch);
?>

In the example above, using the curlshareinit_persistent() function, a handle with the same share options is reused if one already exists — reducing connection setup overhead.

Things to Watch Out For

  • This feature mainly benefits applications that handle a large number of requests per SAPI (Server API).

  • When using shared handles, keep issues such as thread safety and connection cleanup in mind.

  • Make sure your current setup supports this feature (e.g. a suitable cURL version, the way your SAPI is used, etc.).

Other Improvements

PHP 8.5 doesn't just bring the major features above; it also includes many improvements and smaller new features for the overall quality and usability of the language. Here are the highlights:

  • arrayfirst() and arraylast() functions were added: easy ways to get the first or last value of an array.

<?php
$events = ['a','b','c'];
$first = array_first($events);  // 'a'
$last = array_last($events);    // 'c'
?>
  • Fatal errors (such as execution time exceeded) now include a backtrace.

  • The #[\Override] attribute can now be applied to class properties.

  • The #[\Deprecated] attribute can now also be used on traits and constants.

  • Static properties can now have asymmetric visibility.

  • Constructor property promotion now supports marking properties as final.

  • The Closure::getCurrent() method gives access to the current closure from inside an anonymous function.

  • setcookie() and setrawcookie() now support the “partitioned” key.

  • New geterrorhandler() and getexceptionhandler() functions were added.

  • On the DOM API side, Dom\Element::getElementsByClassName() and Dom\Element::insertAdjacentHTML() methods were added.

  • A new grapheme_levenshtein() function was added (for text comparison).

Compatibility and Backward-Incompatible Changes

Like every major release, PHP 8.5 includes some backward-incompatible changes and deprecations. It's important to keep these in mind when upgrading.

Notable Removals / Deprecations

  • The backtick operator (`command`) as an alias for shell_exec() is now deprecated.

  • Cast names such as (boolean), (integer), (double) and (binary) are deprecated; use (bool), (int), (float) and (string) instead.

  • The disable_classes INI setting was removed.

  • Terminating a case statement with ; (instead of :) is deprecated.

  • Using null as an array offset, or using null in arraykeyexists(), is deprecated.

  • Using “array” and “callable” as class alias names with class_alias() is no longer allowed.

  • The magic methods sleep() and wakeup() are soft-deprecated; serialize() and unserialize() are recommended instead.

  • Casting NAN to other types may now emit a warning.

  • Destructuring a non-array value (other than null) with [] or list() now emits a warning.

  • Casting floats or float-like strings to int will emit a warning.

Migration Tips

  • If your codebase has old cast forms such as (integer), converting them to (int) is a good step.

  • Moving parse_url() and similar homegrown URL-parsing code to the new URI extension will pay off in security and maintainability.

  • If you have unused return values, you may run into #[\NoDiscard] warnings; either use the return values or cast them with (void).

  • Check whether your third-party libraries (Composer packages) are PHP 8.5 compatible — some may already use the pipe operator or the clone() additions.

Conclusion

PHP 8.5 doesn't just offer some new syntax; it also takes important steps in terms of the language's readability, developer experience and approach. The URI extension makes URL/URI handling more standards-compliant; the pipe operator enables more functional, fluent code; and features like the clone-with pattern and #[\NoDiscard] support modern coding habits.

The new features offer opportunities to simplify your code and make it safer and easier to maintain.

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more
Software
5 min read

What Is the Repository Pattern?

The Repository pattern is a way of abstracting your business logic away from your data source. It is an extra layer on top of your data-retrieval code and can be used in a variety of ways.

Read more