Dynamic Properties, Property Hooks and Asymmetric Visibility

7.Dynamic Properties, Property Hooks and Asymmetric Visibility

M

In this chapter

We'll learn why dynamic properties are deprecated and the four ways to deal with them, how PHP 8.4's property hooks replace getter-and-setter boilerplate with get and set code on the property itself, how virtual properties compute their value, and how asymmetric visibility like public private(set) makes a property readable everywhere but writable only inside — compared with C#, Kotlin and Swift properties.

17–19 min

The Problem in Real Life

Back to Monday's log: "Deprecated: Creation of dynamic property Booking::$note", thousands of times. An old admin script writes $booking->note = ... on every booking, and Booking has never declared a note property. Since PHP 8.2 that's deprecated; in PHP 9 it will be an error.

Meanwhile Customer has grown six methods — getPhone(), setPhone(), getName() and so on — that do almost nothing. setPhone() was supposed to remove spaces, but one script writes the property directly through a public field left over from Act 11, and reminders to " 07700 900456 " bounce.

M

Six methods just to read and write three fields — and the one rule that matters still gets skipped. Isn't there a better way?

Mia

Getters and Setters vs. Hooks on the Property

Dynamic properties

Writing a property nobody declared is deprecated since PHP 8.2 and will be an error in PHP 9.

Boilerplate

A getter and a setter per field is a lot of code, and a public field next to them makes the setter optional.

Read here, write there

Most data should be readable by everyone and changeable only by the class. That needs two visibilities on one property.

Dynamic Properties, Property Hooks and Asymmetric Visibility

Properties that guard themselves: PHP 8.4 gave properties their own behaviour. This chapter covers:

  • Dynamic properties: why they're deprecated, and how to fix the warnings.
  • Property hooks: get and set code attached to a property.
  • Virtual properties: properties computed from others, with no stored value.
  • Asymmetric visibility: public private(set), readable everywhere, writable inside.
  • Other languages: C# and Kotlin properties, Swift's computed properties and observers.

Dynamic properties and their four fixes: a dynamic property is one written on an object although its class doesn't declare it, like $booking->note. Since PHP 8.2 that's deprecated, because it's almost always a typo or a design shortcut, and PHP 9 will make it an error. There are four fixes. Best: declare the property (public ?string $note = null;). For old classes you can't fix yet, the attribute #[\AllowDynamicProperties] above the class allows them explicitly and silences the warning. To forbid them now, make the class readonly (chapter 1) or give it a throwing __set() (chapter 5). And stdClass (Act 11) still allows them, since that's its whole purpose.

The deprecation, and the four ways to deal with it
<?php
class Booking {}
$b = new Booking();
$b->note = "VIP"; // Deprecated: Creation of dynamic property Booking::$note
class DeclaredBooking // 1. declare it (best)
{
public ?string $note = null;
}
#[\AllowDynamicProperties]
class LegacyBooking {} // 2. allow explicitly, for code you can't fix yet
readonly class StrictBooking {} // 3. forbid: readonly classes throw an Error
// 4. forbid: a __set() that throws (chapter 5)
$d = new DeclaredBooking();
$d->note = "VIP";
$l = new LegacyBooking();
$l->note = "VIP";
echo $d->note, " ", $l->note, "\n"; // VIP VIP — no more deprecations

Getters and setters: until PHP 8.4, a property with a rule meant making it private and writing a getPhone() and a setPhone() with the rule in it — the Java style. It works, but it's a lot of code for every field, and every caller has to remember the methods.

Before 8.4: getters and setters
<?php
declare(strict_types=1);
class Customer
{
private string $phone;
public function __construct(private string $name, string $phone)
{
$this->setPhone($phone);
}
public function getName(): string { return $this->name; }
public function getPhone(): string { return $this->phone; }
public function setPhone(string $phone): void
{
$this->phone = preg_replace('/\s+/', '', $phone); // the one rule
}
}
$clare = new Customer("Clare Lefèvre", " 07700 900456 ");
echo $clare->getPhone(), "\n"; // 07700900456

Property hooks: PHP 8.4 lets you attach code to the property itself. A set hook runs whenever the property is written: public string $phone { set(string $value) { $this->phone = preg_replace('/\s+/', '', $value); } }. Code everywhere keeps writing $customer->phone = "...", and the spaces are removed every time — there's no way around the rule, because there's only the property. Inside the hook, $this->phone means the property's stored value (its backing value). The short form set => trim($value); returns the value to store. A get hook runs whenever the property is read. Hooks can also be added to promoted constructor properties, and interfaces can declare properties with hooks (public string $name { get; }), which Act 11 mentioned. The diagram below follows one write through a set hook.

A write through a set hook

$customer->phone = " 07700 900456 "

any code, anywhere

PHP calls the hook

set(string $value) hook runs

$value = " 07700 900456 "

inside the hook

$this->phone = preg_replace(...)

the hook writes the backing value

result

Stored: "07700900456"

every later read gets the clean value

A set hook: the rule lives on the property
<?php
declare(strict_types=1);
class Customer
{
public string $phone {
set(string $value) {
$this->phone = preg_replace('/\s+/', '', $value); // runs on EVERY write
}
}
public function __construct(public string $name { set => trim($value); }, string $phone)
{
$this->phone = $phone;
}
}
$clare = new Customer(" Clare Lefèvre ", " 07700 900456 ");
echo "[{$clare->name}] [{$clare->phone}]\n"; // [Clare Lefèvre] [07700900456]
$clare->phone = "07700 900 999"; // a direct write still follows the rule
echo $clare->phone, "\n"; // 07700900999

Virtual properties: a property whose hooks never touch its own backing value has no stored value at all: it's virtual. public string $fullName { get => $this->first . " " . $this->last; } is computed from other properties on every read, and since it has no set hook, writing it is an Error: "Property … is read-only". Use virtual properties for values that are always derived — a full name, a total, a formatted price — so they can never get out of date. The diagram below compares a stored property with a virtual one.

Backed property vs. virtual property

public string $phone { set … }

backed: has a stored value

public string $fullName { get … }

virtual: no stored value

behaviour

Read → the stored value

write → set hook → stored

Read → computed from first + last

write → Error: read-only

A virtual property: computed, never stored
<?php
declare(strict_types=1);
class Customer
{
public string $fullName {
get => $this->first . " " . $this->last; // no backing value: virtual
}
public function __construct(public string $first, public string $last) {}
}
$c = new Customer("Clare", "Lefèvre");
echo $c->fullName, "\n"; // Clare Lefèvre
$c->last = "Martin";
echo $c->fullName, "\n"; // Clare Martin: always up to date
try {
$c->fullName = "Someone Else";
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Property Customer::$fullName is read-only
}

Asymmetric visibility: often a property should be readable by everyone but changed only by the class: a booking's status, readable by any screen, changed only through confirm() and cancel(). Before PHP 8.4 that needed a private property plus a getter. Now public private(set) BookingStatus $status says it in one line: public for reading, private for writing. protected(set) allows child classes to write too. Writing from outside is an Error: "Cannot modify private(set) property … from global scope". Readonly properties use the same mechanism: since PHP 8.4 they're implicitly protected(set), so a child class can initialise them.

Asymmetric visibility: public private(set)
<?php
declare(strict_types=1);
enum BookingStatus: string
{
case Pending = "pending";
case Confirmed = "confirmed";
}
class Booking
{
public private(set) BookingStatus $status = BookingStatus::Pending;
public function confirm(): void
{
$this->status = BookingStatus::Confirmed; // inside the class: allowed
}
}
$booking = new Booking();
$booking->confirm();
echo $booking->status->value, "\n"; // confirmed: readable everywhere
try {
$booking->status = BookingStatus::Pending;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
// Cannot modify private(set) property Booking::$status from global scope

How other languages do it: PHP's hooks follow a well-known design. C# has had properties with get and set (and init) since 2002; Kotlin has custom getters and setters with a backing field; JavaScript has get and set accessors; and Swift has computed properties plus property observers, willSet and didSet, which run around a normal assignment. PHP now supports the same thing — computed (virtual) properties and code on get and set — but it has no separate observers: do the "after" work inside the set hook. The table below compares them.

Table — Properties with behaviour, compared
FeaturePHP 8.4+Other languages
Code on writeset hookC#/Kotlin setter, JS set
Code on readget hookC#/Kotlin getter, JS get
Computed, not storedVirtual property (get only)Swift computed property, C# expression-bodied property
Readable outside, writable insidepublic private(set)C#: public string X { get; private set; }
Code before / after a changeNot separate: inside the set hookSwift willSet / didSet
Set only during creationreadonlyC#: init
C#: properties (PHP 8.4's hooks follow this design)
// C# — a property with a rule on set, a computed property, and a private setter
public class Customer
{
private string phone = "";
public string Phone
{
get => phone;
set => phone = value.Replace(" ", "");
}
public string First { get; set; } = "";
public string Last { get; set; } = "";
public string FullName => $"{First} {Last}"; // computed (virtual)
public string Status { get; private set; } = "pending"; // ≈ public private(set)
}

Key Takeaway

Dynamic properties are deprecated since PHP 8.2 (an error in PHP 9): declare the property, allow them explicitly with #[\AllowDynamicProperties], or forbid them with readonly or a throwing __set(). PHP 8.4 property hooks put get and set code on the property itself, so rules can't be skipped and getter/setter boilerplate disappears; a property that only computes is virtual and read-only. Asymmetric visibility — public private(set) or protected(set) — makes data readable everywhere and writable only inside. This is PHP's version of C#/Kotlin properties; Swift's willSet/didSet observers have no separate equivalent.

Why This Matters

Hooks put a property's rules where nobody can miss them: on the property. A phone number is cleaned whether it's set in the constructor, in an admin script or in a test, and dozens of lines of getters and setters disappear.

Asymmetric visibility and fixing dynamic properties are how a PHP 8.4+ codebase stays clean through the upgrade to PHP 9 — and they're what the checkpoint asks you to apply to the booking classes.

note is declared, the log is quiet, Customer lost its six methods, and status is public private(set). One more modern tool: Olivia wants notes limited to 200 characters, and Mia notices that the old oldPrice() function is still called in three places although its doc comment says "@deprecated" — a comment nobody's code ever reads. PHP has real labels that code can read. That's the last chapter: attributes.