Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
PHPTutorial

PHP property hooks and asymmetric visibility: a hands-on tutorial

Replace boilerplate getters and setters with PHP 8.4 property hooks and asymmetric visibility. Build a Product class step by step with validation, computed properties, private(set) and interface properties.

Nilesh Kushvaha

Updated 9 min read

Cloudsoft Zone cover: PHP property hooks and asymmetric visibility: a hands-on tutorial
Image: Cloudsoft Zone
In this article

Most PHP classes written before 2024 are full of small getter and setter methods. They exist for two reasons: to validate or normalise a value when it is written, and to stop outside code from changing a value it should only read. PHP 8.4 added two features that handle both jobs directly on the property: property hooks and asymmetric visibility.

PHP property hooks replace getter and setter methods: a set hook validates input and a get hook computes values. PHP asymmetric visibility, such as public private(set), makes a property readable everywhere but writable only inside the class, and PHP property hooks interface declarations let contracts require them.

In this tutorial you will build a small Product class step by step. You will validate input with a set hook, expose a computed value with a get hook, make properties publicly readable but privately writable, and declare a property in an interface. Along the way you will see the rules and limits described in the PHP manual, so that you know when to use these features and when a plain method is still the better choice.

You need PHP 8.4 or newer. Every example in this article was run on PHP 8.5, the current stable branch in October 2026; the hook and visibility examples behave the same on 8.4.

What property hooks and asymmetric visibility are

A property hook intercepts reads (get) or writes (set) of a single object property. Code outside the class still uses ordinary property syntax, $product->price = 10, but your hook runs in between.

Asymmetric visibility lets a property have one visibility for reading and a stricter one for writing, for example public private(set): anyone can read it, only the class itself can change it.

The PHP manual describes two kinds of hooked property:

  • A backed property stores a value. A property is backed when at least one of its hooks refers to the property itself with $this->propertyName, or when it has no hooks.
  • A virtual property stores nothing. Its hooks compute a value from other data, and it uses no memory in the object.

Step 1: validate input with a set hook

Start with a product name that must not be empty and should not carry stray whitespace. Before PHP 8.4 you would write a private property, a setName() method and a getName() method. With a hook:

PHP
<?php
declare(strict_types=1);

final class Product
{
    public string $name {
        set(string $value) {
            $value = trim($value);
            if ($value === '') {
                throw new InvalidArgumentException('Product name cannot be empty.');
            }
            $this->name = $value;
        }
    }
}

$product = new Product();
$product->name = '  Backup plan  ';
echo $product->name; // Backup plan

$product->name = '   '; // InvalidArgumentException

The property declaration ends with a block instead of a semicolon; that is how PHP knows the property has hooks. Inside the set hook, $this->name = $value writes the real stored value. It does not call the hook again.

When the parameter type is the same as the property type, you can leave it out. The incoming value is then available as $value:

PHP
public int $priceInCents {
    set {
        if ($value < 0) {
            throw new InvalidArgumentException('Price cannot be negative.');
        }
        $this->priceInCents = $value;
    }
}

If the hook only transforms the value, there is a one-line form. The result of the expression is stored:

PHP
public string $currency {
    set => strtoupper($value);
}

Step 2: compute values with a get hook

A display price is derived from the stored price, so it does not need its own storage. A get hook that never refers to $this->displayPrice makes it a virtual property:

PHP
public string $displayPrice {
    get => '$' . number_format($this->priceInCents / 100, 2);
}

Reading $product->displayPrice runs the hook every time, so the value is always in step with priceInCents. Because the property is virtual and has no set hook, writing to it fails with Error: Property Product::$displayPrice is read-only.

A virtual property can also have both hooks. This converter stores only Celsius and exposes Fahrenheit as a read-write view:

PHP
final class Temperature
{
    public float $celsius = 0.0;

    public float $fahrenheit {
        get => $this->celsius * 9 / 5 + 32;
        set {
            $this->celsius = ($value - 32) * 5 / 9;
        }
    }
}

$t = new Temperature();
$t->fahrenheit = 212;
echo $t->celsius; // 100
Hands typing on a laptop keyboard while a code editor is open on the screen
Convert one class at a time: move validation into set hooks and computed getters into virtual properties.

Step 3: read publicly, write privately

Stock levels and identifiers should be visible to other code but changed only through the class's own methods. Asymmetric visibility expresses that directly:

PHP
public private(set) int $stock = 0;

public function receiveStock(int $quantity): void
{
    if ($quantity <= 0) {
        throw new InvalidArgumentException('Quantity must be positive.');
    }
    $this->stock += $quantity;
}

Outside the class, echo $product->stock works, while $product->stock = 99 throws Error: Cannot modify private(set) property Product::$stock from global scope. The manual lists the rules to remember:

  • Only typed properties can have a separate set visibility.
  • The set visibility must be the same as, or stricter than, the read visibility. public protected(set) is allowed; protected public(set) is a syntax error.
  • For public properties you can shorten public private(set) to private(set).
  • A private(set) property is automatically final and cannot be redeclared in a child class.
  • No spaces inside the brackets: private(set), not private( set ).

Use protected(set) when subclasses should be able to write the value:

PHP
class Account
{
    public function __construct(
        public protected(set) string $status = 'active',
    ) {}
}

class SuspendableAccount extends Account
{
    public function suspend(): void
    {
        $this->status = 'suspended'; // allowed: protected(set)
    }
}

Since PHP 8.5, asymmetric visibility also works on static properties, for example public private(set) static int $calls = 0;.

Step 4: declare properties in an interface

PHP 8.4 also allows interfaces to declare properties, as long as they state whether the property must be readable, writable or both. A class can satisfy a read-only interface property with a plain public property, a public private(set) property, a virtual property with a get hook, or a readonly property.

PHP
interface HasSku
{
    public string $sku { get; }
}

The complete class

Putting the steps together gives a class with no getter or setter methods, but with the same guarantees:

PHP
<?php
declare(strict_types=1);

interface HasSku
{
    public string $sku { get; }
}

final class Product implements HasSku
{
    public string $name {
        set(string $value) {
            $value = trim($value);
            if ($value === '') {
                throw new InvalidArgumentException('Product name cannot be empty.');
            }
            $this->name = $value;
        }
    }

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

    public string $displayPrice {
        get => '$' . number_format($this->priceInCents / 100, 2);
    }

    public private(set) int $stock = 0;

    public function __construct(
        public private(set) string $sku,
        string $name,
        int $priceInCents,
    ) {
        $this->name = $name;                 // runs the set hook
        $this->priceInCents = $priceInCents; // runs the set hook
    }

    public function receiveStock(int $quantity): void
    {
        if ($quantity <= 0) {
            throw new InvalidArgumentException('Quantity must be positive.');
        }
        $this->stock += $quantity;
    }
}

$product = new Product('CSZ-001', '  Backup plan  ', 1999);
echo $product->name, PHP_EOL;         // Backup plan
echo $product->displayPrice, PHP_EOL; // $19.99

$product->priceInCents = 2499;
echo $product->displayPrice, PHP_EOL; // $24.99

$product->receiveStock(10);
echo $product->stock, PHP_EOL;        // 10

Notice that name and priceInCents are assigned in the constructor body rather than promoted. Hooks can be declared on promoted constructor properties, but the manual points out that the constructor parameter then uses the property's declared type, regardless of what the set hook would accept. Assigning in the body keeps the validation path identical for construction and later changes.

Light blue plush elephant toy with the Zend logo embroidered on its side, on a white background
Hooks run on every read or write, so keep them small and move heavy work into explicit methods.

Rules and pitfalls

SituationWhat happensWhat to do
Hooks on a readonly propertyNot allowed: hooks are incompatible with readonlyUse private(set) for "read publicly, write internally"
Appending to a hooked array property, $obj->tags[] = 'php'Error: Indirect modification ... is not allowedAssign a whole new array, or add a method such as addTag()
Taking a reference to a hooked propertyWould bypass the set hook, so it is restrictedAvoid references; a &get hook exists for rare cases
Writing to a virtual property without a set hookError: ... is read-onlyIntended; add a set hook only if the write makes sense
Slow work inside a get hookRuns on every readKeep hooks cheap; use an explicit method for expensive calculations
Overriding a hook in a child classAllowed unless the hook or property is finalMark hooks final when subclasses must not change them

The array case surprises most people. Hooks see whole-value writes only, so for collections a method that validates and appends is usually clearer than a hooked array property.

When to use hooks and when not to

  • Use hooks for simple validation, normalisation (trimming, case conversion) and cheap derived values. They remove boilerplate and keep the public API as plain properties.
  • Use asymmetric visibility whenever outside code should read a value but not change it. It replaces most getter-only methods.
  • Use a method when a change has side effects such as saving, dispatching an event or calling an API, or when the operation needs more than one argument. $order->markAsPaid($paymentId) says more than a hooked status property would.
  • Use readonly classes for immutable value objects. On PHP 8.5, combine them with clone($this, [...]) to return modified copies.

If you maintain a library that must also support PHP 8.3 or older, you cannot use these features yet, because they are syntax errors on older versions. Application code that already targets 8.4 or 8.5 can adopt them class by class.

Next steps

Pick one class in your codebase with several trivial getters and setters, and convert it: replace getter-only methods with private(set) properties, move simple validation into set hooks and turn computed getters into virtual properties. Run your tests, check that your static analysis tool understands the new syntax, and then apply the pattern more widely. The property hooks and visibility pages of the PHP manual cover the remaining details, including inheritance and the __PROPERTY__ magic constant.

Frequently asked questions

  • Which PHP version do I need for property hooks?

    Property hooks and asymmetric visibility were introduced in PHP 8.4. They are syntax errors on PHP 8.3 and older.

  • Can I use property hooks on readonly properties?

    No. The PHP manual states that property hooks are incompatible with readonly properties. Use asymmetric visibility such as public private(set) to make a property publicly readable but writable only inside the class.

  • Why does $object->items[] = $value fail on a hooked property?

    Writing to an element of an array property is an indirect modification that would bypass the set hook, so PHP throws an Error for backed array properties with a set hook. Assign a whole new array or add a method that appends.

  • What is the difference between a backed and a virtual property?

    A backed property stores a value; it is backed when a hook refers to the property itself. A virtual property only computes values in its hooks, stores nothing and uses no memory in the object.

Sources

  1. PHP 8.4 Release Announcement — The PHP Group, 2024-11-21
  2. Property Hooks — PHP Manual
  3. Visibility (including asymmetric property visibility) — PHP Manual
  4. Object Interfaces (interface properties) — PHP Manual
  5. PHP 8.5 Release Announcement — The PHP Group, 2025-11-20

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.