Migrating to PHP 8.4 and 8.5: Asymmetric Visibility and Breaking Changes
A practical guide to the PHP 8.4/8.5 syntax additions (property hooks, asymmetric visibility, pipe operator, clone with) with refactoring examples for legacy classes and a checklist of breaking changes to verify before migrating.
PHP ships a new major version every November, and the 2024-2025 window brought two releases that matter a lot for anyone writing object-oriented code: PHP 8.4 (November 21, 2024) introduced property hooks and asymmetric property visibility, two features that genuinely change how you write classes; PHP 8.5 (November 20, 2025) added the pipe operator and the "clone with" pattern, designed to make functional-style code and immutable value objects more readable. Along with the new features come a number of breaking changes worth knowing before upgrading a legacy application.
In this guide we'll look at the most useful syntax additions in PHP 8.4 and 8.5, with refactoring examples from classes written in the "old" style, and a summary of the most common breaking changes to check before migrating.
Why it's worth upgrading
Every PHP version has a support cycle of roughly three years: two years of active fixes (bugs and security) and a third year of security-only patches. Staying on too old a version means losing security updates and, in practice, being unable to upgrade many Composer libraries that keep raising their minimum PHP requirement. The syntax additions in 8.4 and 8.5 aren't just sugar: property hooks and asymmetric visibility let you remove a lot of boilerplate code (hand-written getters and setters) that has sat in virtually every object-oriented PHP class for years.
PHP 8.4: Property Hooks
Property hooks let you attach custom logic to a property's read (get) and write (set) operations, without writing separate getName() / setName() methods. Here's how a classically-styled class gets refactored:
// Before (PHP 8.3 and earlier): manual getters/setters
class LegacyPerson
{
private string $firstName;
private string $lastName;
public function getFullName(): string
{
return $this->firstName . ' ' . $this->lastName;
}
public function setFirstName(string $firstName): void
{
$this->firstName = ucfirst(strtolower($firstName));
}
}
// After (PHP 8.4): property hooks
class Person
{
public string $firstName {
set => ucfirst(strtolower($value));
}
public string $lastName;
// "Virtual" property: has no backing value of its own, exists only as a combination of the others
public string $fullName {
get => $this->firstName . ' ' . $this->lastName;
}
}
$p = new Person();
$p->firstName = 'john';
echo $p->firstName; // "John"
$p->lastName = 'Smith';
echo $p->fullName; // "John Smith"
The main benefit is that from the point of view of code that uses the class, $p->firstName = 'john' remains a plain property assignment, not a method call: the class's API stays clean, while value validation or transformation still happens behind the scenes. A property with only a get hook and no set is effectively a computed read-only property, useful for replacing the many "getter" methods that today simply return a combination of other fields.
PHP 8.4: Asymmetric Property Visibility
Asymmetric visibility lets you set a different visibility level for reading and writing a property. Before PHP 8.4, having a property that's publicly readable but writable only from inside the class necessarily required a getter method:
// Before: a getter just to expose an otherwise private property
class Order
{
private string $status;
public function __construct(string $initialStatus)
{
$this->status = $initialStatus;
}
public function getStatus(): string
{
return $this->status;
}
public function advanceStatus(string $newStatus): void
{
$this->status = $newStatus;
}
}
// After: the protected(set) / private(set) syntax removes the getter
class Order
{
public private(set) string $status;
public function __construct(string $initialStatus)
{
$this->status = $initialStatus; // allowed: we're inside the class
}
public function advanceStatus(string $newStatus): void
{
$this->status = $newStatus;
}
}
$order = new Order('pending');
echo $order->status; // readable from outside: "pending"
$order->status = 'shipped'; // Error: writable only from inside the class
The rule to remember is that write visibility (set) can never be more permissive than read visibility: a public protected(set) property is readable by anyone but writable only by the class and its subclasses, while public private(set) is writable only by the class itself. Combined with property hooks, this feature drastically cuts down the number of "trivial" getters written only to expose a field that would otherwise be private.
PHP 8.4: Other useful additions for refactoring
- New array functions:
array_find(),array_any(),array_all()andarray_find_key()let you search for elements or check conditions on an array without writing a manualforeachloop.$prices = [12.50, 0, 45.90, -3]; $firstNegative = array_find($prices, fn($p) => $p < 0); // -3 $allPositive = array_all($prices, fn($p) => $p >= 0); // false - Parenthesis-free chaining on constructors:
new Cart()->addProduct($p)is now valid without wrappingnew Cart()in parentheses, handy for fluent call chains (builder pattern). - The
#[\Deprecated]attribute: natively marks functions, methods and constants as deprecated, emitting anE_USER_DEPRECATEDnotice to callers, with no need for external libraries to flag the use of legacy internal APIs in a project. - Lazy Objects:
ReflectionClass::newLazyGhost()andnewLazyProxy()let you defer an object's expensive initialization until it's actually used, useful for improving performance with heavy dependencies (connections, external services) that aren't always needed. - New
Dom\namespace: a new DOM API compliant with the WHATWG standard and with native HTML5 support, coexisting with the existingDOMDocument/DOMNodeclasses rather than replacing them.
PHP 8.5: Pipe Operator
The pipe operator (|>) lets you chain a series of function calls left to right, passing each result as the first argument of the next, with no intermediate variables and no nested calls:
// Before: nested calls, read "from the inside out"
$slug = strtolower(str_replace('.', '', str_replace(' ', '-', trim($title))));
// After (PHP 8.5): pipe operator, read left to right
$slug = $title
|> trim(...)
|> (fn($s) => str_replace(' ', '-', $s))
|> (fn($s) => str_replace('.', '', $s))
|> strtolower(...);
The benefit isn't purely cosmetic: with nested calls, understanding what happens to $title means reading the expression from the inside out; with the pipe operator, the sequence of transformations reads in the order they're actually applied — the same principle that makes Unix shell pipelines or chained query-builder methods easy to follow.
PHP 8.5: Clone With
The clone() function now accepts an optional second argument, an associative array of properties to update during cloning. It's particularly useful for readonly classes, where previously the only way to "change" a value was to build a new object by hand, copying every field one by one:
final class Color
{
public function __construct(
public readonly int $red,
public readonly int $green,
public readonly int $blue,
public readonly int $alpha = 255,
) {}
// "Wither" pattern: previously required rebuilding the whole object by hand
public function withAlpha(int $alpha): self
{
return clone($this, ['alpha' => $alpha]);
}
}
$color = new Color(255, 0, 0);
$transparent = $color->withAlpha(128); // new object, same red/green/blue, different alpha
Before PHP 8.5, the same result required calling new self($this->red, $this->green, $this->blue, $alpha), repeating every single field: with objects that have many properties, or when a new field gets added later, this pattern was an easy source of forgotten-field bugs.
PHP 8.5: Other minor additions
array_first()andarray_last(): return the first and last value of an array respectively (ornullif it's empty), without resorting toreset()/end()and their side effects on the array's internal pointer.- The
#[\NoDiscard]attribute: emits a warning when the return value of a marked function is ignored, useful for avoiding common mistakes like forgetting to check the result of a validation function. - Built-in URI extension: a new object-oriented API (namespace
Uri\Rfc3986) for parsing and manipulating URLs, always available without needing external extensions. finalon constructor-promoted properties and support for#[\Override]on properties as well as methods.- Backtraces for fatal errors too, handy in production for understanding the cause of a crash more easily.
Breaking changes to check before migrating
Alongside the new features, every major release brings behavioral changes that can break legacy code. Here are the most common ones to verify before moving to PHP 8.4 or 8.5 in production.
From PHP 8.3 to PHP 8.4
- Implicitly nullable parameters deprecated:
function f(int $x = null) {}now raises a deprecation notice. It must be rewritten explicitly asfunction f(?int $x = null) {}. This is probably the change you'll run into most often when refactoring legacy code, since this pattern was very common in older code. exit()anddie()now behave like real functions: withstrict_typesenabled, passing an incompatible value type now throws aTypeErrorinstead of being silently converted to a string.- Several resources become objects: DBA connections, ODBC results and other things that used to be
resourcevalues are now instances of dedicated classes. Anyis_resource($connection)check needs to be replaced with an appropriate check for the new type (for example$connection !== false). PHP_ZTSandPHP_DEBUGare now booleans instead of integers: a comparison likePHP_ZTS === 1stops working and must be rewritten asPHP_ZTS === true.- Some PDO constants are now boolean (
PDO::ATTR_AUTOCOMMIT,PDO::ATTR_EMULATE_PREPARES): better to passtrue/falserather than1/0. - JIT disabled by default: the default configuration changes from
opcache.jit=tracingtoopcache.jit=disable. If you previously enabled JIT by setting onlyopcache.jit_buffer_size, you now also need to explicitly setopcache.jit. round()with an invalid mode now throws aValueErrorinstead of silently falling back toPHP_ROUND_HALF_UP.
From PHP 8.4 to PHP 8.5
- Backtick as an alias for
shell_exec()deprecated: the rarely-used backtick operator (`` `command` ``) for running shell commands is now deprecated in favor of the explicit function. - Non-canonical casts deprecated:
(boolean),(integer),(double)and(binary)are deprecated in favor of the canonical forms(bool),(int),(float)and(string). nullas an array offset deprecated: writing$array[null]to mean the empty string key""now raises a notice.
A practical migration strategy
For a non-trivial legacy application, it's better to go one step at a time rather than jumping straight to the latest version:
- Update your Composer dependencies first to the latest version compatible with your current PHP, even before changing PHP version: many libraries only support a new PHP release a few weeks after it ships.
- Run the application in a staging environment on the new version, with
error_reporting(E_ALL)and error display turned on, so deprecation notices surface immediately instead of being discovered in production. - Use a static analysis tool (PHPStan or Psalm, with rules updated to the latest PHP version) to automatically spot code that uses deprecated or removed functionality, without having to manually exercise every code path.
- Run the full automated test suite on the new version before any deployment: the breaking changes listed above (resources becoming objects, boolean PDO constants,
round()behavior) are almost always caught by tests that already cover existing edge cases. - Migrate one environment at a time (staging first, then a slice of production if your infrastructure allows it) rather than upgrading every server at once, so an unexpected issue stays contained.
- Adopt the new features gradually: there's no need to immediately rewrite every existing class with property hooks and asymmetric visibility. Introduce them in new code, and when you happen to touch a legacy class for other reasons, consider whether it's worth simplifying it while you're there.
Conclusion
PHP 8.4 and 8.5 add concrete tools for writing leaner classes: property hooks and asymmetric visibility remove most hand-written getters and setters, while the pipe operator and clone-with-array make, respectively, transformation chains and the creation of immutable-object variants more readable. The price to pay is the usual attention to the breaking changes that come with every annual release: the combination of staging, static analysis and automated tests remains the safest way to handle the migration without production surprises.
Official sources
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0