Programming languages · Intermediate · 22 min
Use the new features in PHP 8.5: the pipe operator, clone with and more
By Padding · Updated 18 Nov 2026
PHP 8.5.13 · php:8.5-cli image (Debian 13) · Ubuntu 26.04 ships PHP 8.5.4
You will rewrite a slug-and-validate routine with the PHP 8.5 pipe operator, then try clone with, array_first and array_last, the URI extension, NoDiscard, closures in constant expressions and the new deprecations, each as a small script you run on the command line.
On this page
PHP 8.5 came out in November 2025, and it is the version Ubuntu 26.04 ships. It adds one piece of syntax that changes how everyday code reads, the pipe operator |>, plus a handful of smaller features you will start to meet in Laravel, Symfony and library code: clone with property updates, array_first() and array_last(), a built-in URI parser, the #[\NoDiscard] attribute and closures in constant expressions. It also deprecates some old syntax, which shows up as warnings in existing code.
You work in a throwaway folder, ~/php85-demo. Each step writes one short script with a heredoc and runs it with the php command, so you can paste the commands or type the files into an editor. Everything here works on any PHP 8.5 release. PHP 8.6.0 was released in November 2026; the features below carry over unchanged.
Step 1 · Check your PHP version and make a work folder
If PHP is not installed yet, follow Hello World in PHP first. Then check the version and create the folder:
php --version
mkdir -p ~/php85-demo
cd ~/php85-demoCheck it worked
The first line of the output starts with PHP 8.5., for example PHP 8.5.4 (cli) on Ubuntu 26.04 or PHP 8.5.13 (cli) with the upstream build. If it says 8.4 or older, the scripts below stop with a parse error at the first new piece of syntax.
Step 2 · Rewrite a slug routine with the pipe operator
A slug is the readable part of a URL, such as jollof-rice-plantain in /recipes/jollof-rice-plantain. Here is the kind of function you find in older code. It works, but you have to read it inside out, starting from the innermost call:
cat > slug-old.php <<'PHP'
<?php
function slugify(string $title): string
{
$slug = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower(trim($title))), '-');
if ($slug === '') {
throw new InvalidArgumentException("No usable characters in '$title'");
}
return $slug;
}
echo slugify(' Jollof Rice & Plantain: 8.5 Edition '), "\n";
PHP
php slug-old.phpThe pipe operator passes the value on its left as the only argument to the callable on its right. A chain of pipes runs top to bottom, in the order you read it. Rewrite the function so each transformation is one line, and move the validation into the chain as its own small function:
cat > slug.php <<'PHP'
<?php
function requireSlug(string $slug): string
{
if ($slug === '') {
throw new InvalidArgumentException('No usable characters for a slug');
}
return $slug;
}
function slugify(string $title): string
{
return $title
|> trim(...)
|> strtolower(...)
|> (fn(string $s) => preg_replace('/[^a-z0-9]+/', '-', $s))
|> (fn(string $s) => trim($s, '-'))
|> requireSlug(...);
}
echo slugify(' Jollof Rice & Plantain: 8.5 Edition '), "\n";
try {
slugify('!!!');
} catch (InvalidArgumentException $e) {
echo 'rejected: ', $e->getMessage(), "\n";
}
PHP
php slug.phpThree rules explain the shape of that chain:
- The right-hand side must be a callable that takes one argument.
trim(...)is first-class callable syntax: it turns the function into aClosurewithout calling it. - When a step needs more than one argument, such as
preg_replace, wrap it in an arrow function. The arrow function must sit in parentheses, or PHP reads the rest of the chain as part of its body. - Functions that take their argument by reference, such as
sort(), cannot go on the right of|>. Wrap them in a closure that copies the array, sorts it and returns it.
An exception thrown anywhere in the chain stops it, exactly as it would in nested calls, so requireSlug acts as a guard at the end.
The pattern [^a-z0-9]+ keeps ASCII letters only. A title in Yoruba, Hausa or French loses its accented letters (Ẹ̀fọ́ riro becomes f-riro). If your users write in those languages, add a step that transliterates first, for example with the intl extension's transliterator_transliterate(), or keep Unicode letters with /[^\p{L}\p{N}]+/u and mb_strtolower(...).
Check it worked
Both scripts print jollof-rice-plantain-8-5-edition. The new one also prints rejected: No usable characters for a slug. If you see a parse error, something like syntax error, unexpected token ">", your php is older than 8.5.
Step 3 · Update readonly objects with clone with
Readonly classes are a good fit for value objects such as money, but changing one field used to mean rebuilding the whole object by hand. In PHP 8.5, clone() takes a second argument: an array of property names and new values, applied to the copy.
cat > price.php <<'PHP'
<?php
final readonly class Price
{
public function __construct(
public int $amountMinor,
public string $currency,
) {}
public function withAmount(int $amountMinor): static
{
return clone($this, ['amountMinor' => $amountMinor]);
}
public function format(): string
{
return sprintf('%s %s', $this->currency, number_format($this->amountMinor / 100, 2));
}
}
$base = new Price(450000, 'NGN');
$sale = $base->withAmount(399900);
echo $base->format(), "\n";
echo $sale->format(), "\n";
try {
$hack = clone($base, ['amountMinor' => 1]);
} catch (Error $e) {
echo 'blocked outside the class: ', get_class($e), "\n";
}
PHP
php price.phpclone with updates follows the same visibility rules as assigning a property. Inside the class, withAmount() may set the readonly property on the fresh copy. Outside it, the same call throws an Error, because readonly properties can only be written from within their class. That keeps the "with-er" methods as the one place your object can change. Store money in minor units (kobo, cents) as integers, as here, so you never round floats.
Check it worked
The output is NGN 4,500.00, then NGN 3,999.00, then blocked outside the class: Error. The first line shows the original object did not change.
Step 4 · Read the ends of an array with array_first and array_last
Getting the first or last value used to need reset(), end() or array_key_first() plus an index lookup. The two new functions return the value directly, ignore what the keys are, and return null for an empty array, which pairs with ??:
cat > ends.php <<'PHP'
<?php
$orders = [
'ord-104' => 'Lagos',
'ord-107' => 'Accra',
'ord-112' => 'Nairobi',
];
echo array_first($orders), "\n";
echo array_last($orders), "\n";
echo array_last([]) ?? 'no orders yet', "\n";
PHP
php ends.phpNeither function moves the array's internal pointer, so they are safe to call in the middle of other code.
Check it worked
The output is Lagos, Nairobi and no orders yet, one per line.
Step 5 · Parse URLs with the URI extension
parse_url() follows no standard and accepts strings that browsers reject, and the reverse. PHP 8.5 includes a URI extension that is always available, with two classes for two standards: Uri\Rfc3986\Uri follows RFC 3986, the generic URI rules, and Uri\WhatWg\Url follows the WHATWG URL standard that browsers use. Both are immutable: the with...() methods return a new object.
cat > urls.php <<'PHP'
<?php
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
$uri = new Uri('https://shop.example/search?q=rice&page=2');
echo $uri->getHost(), ' ', $uri->getPath(), ' ', $uri->getQuery(), "\n";
$base = new Uri('https://shop.example/blog/post/');
echo $base->resolve('../img/logo.svg')->toString(), "\n";
$typed = 'https://shop.example/search?q=jollof rice';
var_dump(Uri::parse($typed));
echo Url::parse($typed)->toAsciiString(), "\n";
$cafe = new Url('https://café.example/menu');
echo $cafe->getAsciiHost(), ' ', $cafe->getUnicodeHost(), "\n";
PHP
php urls.phpWhat each part shows:
- The getters return each component, and
resolve()turns a relative link into a full one, following the standard's rules for..segments. - A URL with a raw space is invalid under RFC 3986, so
Uri::parse()returnsnull. A browser accepts it and percent-encodes the space, andUrl::parse()does the same. Use the WHATWG class for anything a person typed into a browser-style field, and the RFC 3986 class for strict checks on machine-generated URIs. newthrows an exception for an invalid string, whileparse()returnsnull. Pick the form that matches how you want to handle bad input.- Hostnames in other scripts are stored in their ASCII form (Punycode) on the network.
getUnicodeHost()gives back the readable form to show your users.
Check it worked
The output has five lines: shop.example /search q=rice&page=2, https://shop.example/blog/img/logo.svg, NULL, https://shop.example/search?q=jollof%20rice and xn--caf-dma.example café.example. If you get Class "Uri\Rfc3986\Uri" not found, you are on PHP 8.4 or older.
Step 6 · Mark results that must be used with NoDiscard
Some return values are the whole point of a call: a new immutable object, a success flag, a computed total. Forgetting to use one is a silent bug. Add #[\NoDiscard] to such a function and PHP warns whenever a caller throws the result away. Cast to (void) when you mean to ignore it.
The command below turns on every warning for this one run, because production php.ini settings often hide some of them. log_errors=0 stops PHP also sending each warning to its error log, which on the command line is your terminal, so you see every message once instead of twice (once as PHP Warning:, once as Warning:):
cat > nodiscard.php <<'PHP'
<?php
#[\NoDiscard('the total is the only output')]
function totalMinor(array $lines): int
{
return array_sum(array_column($lines, 'amountMinor'));
}
$lines = [['amountMinor' => 120000], ['amountMinor' => 35000]];
totalMinor($lines);
(void) totalMinor($lines);
echo totalMinor($lines), "\n";
PHP
php -d error_reporting=-1 -d display_errors=1 -d log_errors=0 nodiscard.php 2>&1The optional message in the attribute is added to the warning, so it can tell the caller why the value matters. The attribute works on methods too, which is where you will meet it most: a with...() method on an immutable object whose result is ignored almost always means a bug.
Check it worked
You see exactly one warning, for line 11, that starts Warning: The return value of function totalMinor() and includes your message, the total is the only output. Then comes 155000. The (void) line on line 12 produces no warning.
Step 7 · Put closures in constants and default values
Constant expressions (constant values, default values of parameters and properties, attribute arguments) can now hold static closures and first-class callables. That lets a function take an optional callback with a real default instead of null plus an if:
cat > constexpr.php <<'PHP'
<?php
final class Slugs
{
public const LOWER = strtolower(...);
}
function slugWith(
string $title,
Closure $clean = static function (string $s): string {
return trim(preg_replace('/[^a-z0-9]+/', '-', $s), '-');
},
): string {
return $title |> Slugs::LOWER |> $clean;
}
echo slugWith('Market Day Prices'), "\n";
echo slugWith('Market Day Prices', static fn(string $s) => str_replace(' ', '_', $s)), "\n";
PHP
php constexpr.phpA closure in a constant expression must be static, cannot capture variables with use, and cannot be an arrow function, because arrow functions capture their surroundings automatically. A callable stored in a constant works on the right of |> like any other.
Check it worked
The output is market-day-prices with the default cleaner, then market_day_prices with the one passed in.
Step 8 · Find the new deprecations in older code
Upgrading to 8.5 does not break code that uses the deprecated syntax, but it prints deprecation notices, and a later major version will remove it. Save a file with the four you are most likely to find in an older codebase:
cat > old.php <<'PHP'
<?php
$count = (integer) '3';
$host = `hostname`;
switch ($count) {
case 3;
echo "three\n";
break;
}
$totals = [];
$totals[null] = 10;
PHP
php -d error_reporting=-1 -d display_errors=1 -d log_errors=0 old.php 2>&1Each line has a direct replacement:
(integer),(boolean),(double)and(binary)become(int),(bool),(float)and(string).- The backtick operator becomes an explicit
shell_exec()call, which is also easier to spot in a security review. case 3;becomescase 3:.nullas an array key becomes'', which is what PHP always turned it into.
Also on the list: __sleep() and __wakeup() are soft-deprecated in favour of __serialize() and __unserialize(). Soft-deprecated means no notice yet, so search for them by name. Write the fixed version:
cat > fixed.php <<'PHP'
<?php
$count = (int) '3';
$host = shell_exec('hostname');
switch ($count) {
case 3:
echo "three\n";
break;
}
$totals = [];
$totals[''] = 10;
PHP
php -d error_reporting=-1 -d display_errors=1 -d log_errors=0 fixed.php 2>&1To sweep a real project, run grep -rnE '\((integer|boolean|double|binary)\)|case [^:]*;$|__sleep|__wakeup' src/ and run your test suite with -d error_reporting=-1 -d display_errors=1 -d log_errors=0 so the remaining notices appear, once each. Without log_errors=0, each notice can appear twice on the command line: once from the error log (prefixed PHP Deprecated:) and once from the displayed output.
Check it worked
old.php prints four Deprecated: notices (one each for the cast, the backtick, the case and the null key) and three. fixed.php prints only three.
Step 9 · Clean up
Remove the demo folder. PHP stays installed:
cd ~
rm -rf ~/php85-demoCheck it worked
ls ~/php85-demo reports No such file or directory.
Next steps
- Put these features to work in a typed domain model: write safer PHP with strict types, enums and readonly classes.
- Turn the scripts into a package with tests: manage PHP dependencies and autoloading with Composer.
- Build a web application on PHP 8.5: install Laravel 13 on Ubuntu 26.04.
- The full list of 8.5 changes, including final promoted properties,
#[\Override]on properties andClosure::getCurrent(), is in the PHP 8.5 migration guide in the PHP manual.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials