PHP Advent

#[Language]

PHP Property Hooks and Asymmetric Visibility in PHP 8.4

· 14 min read

A bright modern developer desk in early morning light featuring an ultrawide monitor displaying abstract code layouts beside a split mechanical keyboard, an open notebook with flowchart trees, and a brass sand timer.

PHP 8.4 property hooks let you put get and set logic on a property declaration. You can validate a write or change what a read returns without writing separate getter and setter methods. Asymmetric visibility controls who can write to the property: callers can read it publicly while only the class or its subclasses can change it. You no longer need a custom getter or a readonly workaround for that access pattern.

Before PHP 8.4, validation and derived values meant making properties private and writing methods such as getName() and setName(). For public reads with restricted writes, you used private properties with manual getters or readonly, which prevented any mutation after initialization. PHP 8.4 supports these access patterns in the language itself, with features inspired by Kotlin, C#, and Swift.

The full specifications and release details are in the PHP 8.4 release announcement, the Property Hooks RFC, and the Asymmetric Visibility v2 RFC.

The Problems with Traditional Accessors and Magic Methods

For years, building domain entities or data transfer objects meant choosing among three approaches, each with a drawback:

  1. Public properties are simple and concise, but any consumer can assign invalid data or change internal state unexpectedly. There is no encapsulation.
  2. Getters and setters preserve encapsulation, but each property requires five to ten lines of boilerplate methods. In a model with ten properties, half the class file is repetitive accessors. The business logic gets harder to find.
  3. Magic __get() and __set() methods intercept access dynamically and avoid repetitive methods. The cost is weaker type safety, IDE autocompletion, and static analysis. Magic access also adds runtime overhead and makes debugging traces harder to follow.

Property hooks keep public property syntax while letting you enforce validation rules as you would in dedicated methods.

Understanding Property Hooks Syntax

A property hook intercepts reads (get) or writes (set) for one class property. Declare the hooks inside braces directly after the property declaration.

PHP 8.4 supports two styles of hooks:

  1. Expression body (arrow syntax): Uses => for concise, single-expression logic.
  2. Statement body (block syntax): Uses { ... } for multi-line logic with explicit statements.

The official syntax rules are detailed in the PHP manual on property hooks.

This class uses both styles:

<?php

class CustomerProfile
{
    public string $username {
        set => strtolower(trim($value));
        get => '@' . $this->username;
    }

    public string $email {
        set (string $value) {
            $sanitized = filter_var($value, FILTER_SANITIZE_EMAIL);
            if (!filter_var($sanitized, FILTER_VALIDATE_EMAIL)) {
                throw new InvalidArgumentException('Invalid email address provided.');
            }
            $this->email = strtolower($sanitized);
        }
        get {
            return $this->email;
        }
    }
}

$profile = new CustomerProfile();
$profile->username = '  AlexDev  ';
$profile->email = 'User@Example.Com';

var_dump($profile->username);
// string(8) "@alexdev"

var_dump($profile->email);
// string(16) "user@example.com"

The $username property uses arrow syntax for its set hook. If you omit the parameter list in set, PHP supplies $value with the same type as the property. The $email property uses statement bodies to validate the input before writing it to storage.

Backed Versus Virtual Properties

A backed property has its own storage in memory. If a hook accesses that storage through $this->propertyName, the property is backed. Properties without hooks are backed too. They use standard object memory and can have default values.

A virtual property has no storage of its own: none of its hooks access its own storage. It behaves like a calculated method that callers access with property syntax. With no memory allocated for the property, there is nowhere to keep a default value, so virtual properties cannot have one.

Before and After: Derived Full Name

Consider an object that presents a full name derived from first and last names.

In PHP 8.3 and earlier, calculating derived state required a dedicated method:

<?php

class User
{
    public function __construct(
        public string $firstName,
        public string $lastName,
    ) {}

    public function getFullName(): string
    {
        return trim($this->firstName . ' ' . $this->lastName);
    }
}

$user = new User('Jane', 'Doe');
var_dump($user->getFullName());
// string(8) "Jane Doe"

In PHP 8.4, a virtual property exposes the derived value using property access, eliminating method call parentheses:

<?php

class User
{
    public function __construct(
        public string $firstName,
        public string $lastName,
    ) {}

    public string $fullName {
        get => trim($this->firstName . ' ' . $this->lastName);
    }
}

$user = new User('Jane', 'Doe');
var_dump($user->fullName);
// string(8) "Jane Doe"

Virtual properties calculate their value on demand. When $user->fullName is accessed, the get hook evaluates and returns the concatenated string. No memory is allocated for $fullName itself.

A wooden workbench contrasts a solid carved dark walnut storage block on the left with an optical glass prism focusing daylight into a spectral beam on the right.

Asymmetric Visibility in Depth

Asymmetric visibility controls who can read and write a property. Hooks control what happens when they do.

Before PHP 8.4, a visibility declaration applied equally to reads and writes. Declaring a property public let outside code both read and change it. If you wanted to allow reads but prevent outside writes, you made the property private or protected and wrote a public getter.

PHP 8.4 introduces asymmetric visibility, detailed in the PHP manual on visibility. You specify the read visibility first, followed by the write visibility in parentheses:

  • public private(set): Readable everywhere, writable only inside the defining class.
  • public protected(set): Readable everywhere, writable only inside the defining class and its subclasses.
  • protected private(set): Readable in subclasses, writable only inside the defining class.

A private(set) property is also implicitly final, so a child cannot redeclare it. A protected(set) property can be redeclared if the child keeps or widens both access levels. These rules matter when choosing a property for an extensible base class.

If read visibility is public, the leading public keyword can be omitted: private(set) string $name; is identical to public private(set) string $name;.

Key Rules for Asymmetric Visibility

Three rules apply to these declarations:

  • The property must have an explicit type declaration. Untyped properties cannot use asymmetric visibility.
  • Write visibility cannot be more permissive than read visibility. A declaration like private public(set) causes a compile error.
  • You can use asymmetric visibility with constructor property promotion.

The constructor can declare the properties and their access restrictions together:

<?php

class OrderItem
{
    public function __construct(
        public private(set) string $sku,
        public private(set) int $quantity,
        public protected(set) int $unitPriceCents,
    ) {}

    public function applyDiscount(int $discountCents): void
    {
        if ($discountCents > $this->unitPriceCents) {
            throw new InvalidArgumentException('Discount cannot exceed unit price.');
        }
        $this->unitPriceCents -= $discountCents;
    }
}

$item = new OrderItem('WIDGET-01', 2, 1500);

var_dump($item->sku, $item->quantity, $item->unitPriceCents);
// string(9) "WIDGET-01"
// int(2)
// int(1500)

$item->applyDiscount(200);
var_dump($item->unitPriceCents);
// int(1300)

External callers can read $item->sku and $item->unitPriceCents without getters. But an assignment such as $item->quantity = 5; from outside the class immediately throws an Error: a private(set) property cannot be changed from the global scope.

Before and After: Refactoring an Active Domain Model

To see how property hooks and asymmetric visibility combine in real code, consider an active domain model. In this scenario, a BankAccount entity tracks an account number, a current balance, an account status, and a transaction counter.

Before: Traditional Getters, Setters, and Private Fields

In PHP 8.3 and earlier, keeping internal control over mutations while exposing state required extensive boilerplate:

<?php

class BankAccount
{
    private string $accountNumber;
    private int $balanceCents;
    private string $status;
    private int $transactionCount = 0;

    public function __construct(string $accountNumber, int $initialDepositCents)
    {
        $this->accountNumber = strtoupper(trim($accountNumber));
        if ($initialDepositCents < 0) {
            throw new InvalidArgumentException('Initial deposit cannot be negative.');
        }
        $this->balanceCents = $initialDepositCents;
        $this->status = 'active';
    }

    public function getAccountNumber(): string
    {
        return $this->accountNumber;
    }

    public function getBalanceCents(): int
    {
        return $this->balanceCents;
    }

    public function getStatus(): string
    {
        return $this->status;
    }

    public function getTransactionCount(): int
    {
        return $this->transactionCount;
    }

    public function deposit(int $amountCents): void
    {
        if ($amountCents <= 0) {
            throw new InvalidArgumentException('Deposit amount must be positive.');
        }
        $this->balanceCents += $amountCents;
        $this->transactionCount++;
    }

    public function withdraw(int $amountCents): void
    {
        if ($amountCents <= 0) {
            throw new InvalidArgumentException('Withdrawal amount must be positive.');
        }
        if ($amountCents > $this->balanceCents) {
            throw new RuntimeException('Insufficient funds available.');
        }
        $this->balanceCents -= $amountCents;
        $this->transactionCount++;
    }
}

After: Streamlined Domain Model with Hooks and Asymmetric Visibility

In PHP 8.4, asymmetric visibility exposes the properties directly for reading while preventing unauthorized external modification. A property hook normalizes the account number on assignment:

<?php

class BankAccount
{
    public private(set) string $accountNumber {
        set => strtoupper(trim($value));
    }

    public private(set) int $balanceCents;
    public private(set) string $status = 'active';
    public private(set) int $transactionCount = 0;

    public function __construct(string $accountNumber, int $initialDepositCents)
    {
        $this->accountNumber = $accountNumber;
        if ($initialDepositCents < 0) {
            throw new InvalidArgumentException('Initial deposit cannot be negative.');
        }
        $this->balanceCents = $initialDepositCents;
    }

    public function deposit(int $amountCents): void
    {
        if ($amountCents <= 0) {
            throw new InvalidArgumentException('Deposit amount must be positive.');
        }
        $this->balanceCents += $amountCents;
        $this->transactionCount++;
    }

    public function withdraw(int $amountCents): void
    {
        if ($amountCents <= 0) {
            throw new InvalidArgumentException('Withdrawal amount must be positive.');
        }
        if ($amountCents > $this->balanceCents) {
            throw new RuntimeException('Insufficient funds available.');
        }
        $this->balanceCents -= $amountCents;
        $this->transactionCount++;
    }
}

The refactored version eliminates four boilerplate getter methods without altering any behavior or business rule. External callers access $account->balanceCents directly instead of calling $account->getBalanceCents(), while mutations remain strictly controlled through the deposit() and withdraw() domain methods.

A split workbench view contrasts a complex assembly of tangled copper wiring on the left with a streamlined, compact architectural module on the right.

Interaction with Readonly Properties

PHP 8.1 introduced readonly for properties that can be written once. It still suits strictly immutable value objects. Choosing it over asymmetric visibility depends on whether the value must stay fixed or the class needs to change it later.

Property Hooks Are Incompatible with Readonly

You cannot place property hooks on a readonly property. A declaration like public readonly string $title { get => $this->title; } produces a fatal compilation error. You can combine readonly with asymmetric visibility when the declared access levels permit it, but the property still has the write-once rule.

The readonly keyword guarantees at most one initialization write and no changes afterward. Hooks run logic when a property is assigned or read. PHP 8.4 rejects the combination, so choose a hooked mutable property or a readonly property according to the access contract you need.

Choosing Between Readonly and Asymmetric Visibility

Choose between readonly and public private(set) based on how the object uses the value:

  • Use readonly when a property represents immutable data that must never change after construction. This includes value objects like UUID identifiers, currency codes, and timestamp snapshots.
  • Use public private(set) when a property belongs to a mutable entity whose internal state changes over its lifecycle, such as order statuses, cached calculations, and counters.
  • Use public private(set) when you need to assign a default value to an uninitialized property. In PHP, typed readonly properties cannot have default values because a default value locks the property upon declaration, preventing constructor assignment.

Immutability and visibility answer different questions: whether a value can change, and who can change it. Our overview of PHP 8.5 features covers clone with, which builds on these features for immutable objects.

Declaring Properties in Interfaces

Before PHP 8.4, interfaces could only declare methods. To require access to data, an interface had to specify a getter such as getName(): string.

PHP 8.4 allows interfaces to declare public properties by specifying hook requirements:

  • { get; }: Implementing classes must provide public read access.
  • { set; }: Implementing classes must provide public write access.
  • { get; set; }: Implementing classes must provide both public read and write access.

Both classes below satisfy the same interface, though they implement its properties differently:

<?php

interface AuditableEntity
{
    public string $identifier { get; }
    public string $status { get; set; }
}

class Invoice implements AuditableEntity
{
    // Satisfies { get; } with a virtual property hook
    public string $identifier {
        get => 'INV-' . $this->invoiceNumber;
    }

    // Satisfies { get; set; } with standard backed property access
    public string $status;

    public function __construct(
        private int $invoiceNumber,
        string $status = 'draft'
    ) {
        $this->status = $status;
    }
}

class Receipt implements AuditableEntity
{
    // Satisfies { get; } with asymmetric visibility
    public private(set) string $identifier;

    // Satisfies { get; set; } with backed hooks that validate input
    public string $status {
        set {
            if (!in_array($value, ['pending', 'settled', 'voided'], true)) {
                throw new InvalidArgumentException('Invalid receipt status.');
            }
            $this->status = $value;
        }
        get => $this->status;
    }

    public function __construct(string $identifier, string $status = 'pending')
    {
        $this->identifier = $identifier;
        $this->status = $status;
    }
}

Invoice satisfies { get; } with a virtual hook. Receipt uses a public private(set) property instead. Both allow public callers to read the property, which is all the interface requires. The class decides how to store or calculate the value.

Inheritance, Overriding, and Parent Hooks

Property hooks follow class inheritance much like methods do. A child class can override a hook or add hooks to a parent property. It can also call the parent implementation.

Overriding and Accessing Parent Hooks

When overriding a hook in a child class, you can invoke the parent implementation using parent::$propertyName::hookName():

<?php

class BaseMetric
{
    public int $value {
        set (int $value) {
            if ($value < 0) {
                throw new InvalidArgumentException('Metric value cannot be negative.');
            }
            $this->value = $value;
        }
        get => $this->value;
    }
}

class BoundedMetric extends BaseMetric
{
    public int $value {
        set (int $value) {
            if ($value > 1000) {
                throw new InvalidArgumentException('Metric exceeds maximum limit of 1000.');
            }
            parent::$value::set($value);
        }
    }
}

$metric = new BoundedMetric();
$metric->value = 500;
var_dump($metric->value);
// int(500)

If a child class overrides only the set hook, the parent's get hook is inherited automatically. To verify that an override matches an existing parent hook, you can apply the standard #[\Override] attribute directly to the hook.

Preventing Overrides with the Final Keyword

You can prevent child classes from overriding hooks by applying the final keyword:

  • At the property level: public final string $code { ... } prevents child classes from altering the property or any of its hooks.
  • At the hook level: Marking an individual hook final allows child classes to override other hooks while locking that specific behavior:
<?php

class SystemToken
{
    public string $token {
        final get => hash('sha256', $this->token);
        set => trim($value);
    }
}

Static Analysis and Tooling Integration

When adding property hooks, running static analysis as part of your continuous integration pipeline helps inspect code alongside your automated tests. If you are introducing an analyzer to an existing project, see our guide to adding PHPStan to a legacy codebase.

For exceptions in validation hooks, write clear sentences that explain why the assignment failed. Callers should be able to understand the rejection without reading the hook implementation.

When a Plain Method is Still Clearer

Property hooks suit lightweight data access, transformation, and validation. Putting heavier work in a hook can surprise callers with side effects or performance regressions that are hard to diagnose. Keep an explicit method for operations that involve:

  • Network or disk I/O: A property access like $order->shippingStatus should never trigger an HTTP request to a logistics API. Callers expect property reads to return immediately from local memory.
  • Heavy computational cost: Calculating cryptographic proofs or parsing large datasets should remain in explicit methods like $document->parseContent().
  • Significant side effects: Operations that write to a database, send notification emails, or dispatch domain events should always be explicit methods like $cart->checkout().
  • Multiple arguments or variable parameters: Hooks support only a single value for set and take no arguments for get.
  • Operations that may fail with multiple recovery paths: When an operation can fail in several distinct ways that the caller needs to handle separately, a method returning a result object or distinct error codes is clearer.

In the first class below, reading a property hides work proportional to the data size. The second class makes that work explicit with a method call:

<?php

// Avoid: Property hook hiding a full scan
class UnoptimizedReport
{
    public function __construct(private array $rows) {}

    public array $data {
        get {
            return array_values(array_filter($this->rows, fn (int $row): bool => $row > 0));
        }
    }
}

// Prefer: Explicit method signaling the scan
class ExplicitReport
{
    public function __construct(private array $rows) {}

    public function loadAnalytics(): array
    {
        return array_values(array_filter($this->rows, static fn (int $row): bool => $row > 0));
    }
}

$report = new ExplicitReport([-2, 3, 5]);
assert($report->loadAnalytics() === [3, 5]);

Common Mistakes to Avoid

  • Accidental recursion through another property: Inside its own hook, $this->prop accesses backing storage without calling that hook again. Accessing a different hooked property still calls its hook, so two hooks that call each other can loop.
An open engineering notebook shows hand-drawn circular flowchart pathways crossed out in red next to a direct forward pathway leading to a green indicator mark.
  • Modifying untyped properties with asymmetric visibility: PHP requires asymmetric visibility properties to declare an explicit type. Declaring public private(set) $untyped; triggers a fatal compilation error.
  • Assuming private(set) makes an object immutable: Asymmetric visibility restricts who can write to a property, not how many times it can be written. Internal methods can reassign a private(set) property repeatedly throughout the object's life.
  • Hiding side effects inside get hooks: A get hook should be idempotent and free of unexpected side effects. Modifying other properties, writing logs, or altering database state during a property read violates expectations and makes debugging difficult.
  • Forgetting that virtual properties lack storage: Attempting to assign to a virtual property that defines only a get hook produces a fatal error. If an external caller needs to write to a virtual property, you must provide a matching set hook that distributes the incoming value to the appropriate backing properties.

Frequently Asked Questions

Can property hooks be used with references?

Usually not. A normal get hook cannot return a reference, so reference assignment and indirect array modification do not work as they do with a plain property. PHP allows an explicit &get hook for cases that need a reference. A backed property cannot have both &get and set, because reference writes would bypass the setter. See the manual's reference rules before using this exception.

How do property hooks affect serialization and json_encode?

json_encode() and native serialize() include only backed properties by default. Virtual properties have no stored value in the object instance, so they do not appear in the serialized output. If you want virtual properties included in JSON output, implement the JsonSerializable interface and return an array containing the virtual properties.

How do isset() and empty() interact with property hooks?

If the property has a get hook, isset() and empty() call it and test its return value. A get hook that reads uninitialized backing storage throws an Error even under isset(). If a backed property has no get hook, PHP checks its backing value directly. A set-only virtual property cannot be read this way. unset() on any hooked property also throws an Error.

Can static properties use asymmetric visibility or hooks in PHP 8.4?

In PHP 8.4, both features apply only to instance properties; static properties cannot use asymmetric visibility or hooks. The language roadmap addressed asymmetric visibility for static properties separately for PHP 8.5.