Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 147 ยท Object-Oriented PHP

Property Hooks and Asymmetric Visibility

Learn PHP 8.4 property hooks - get and set hooks, virtual properties, validation - plus asymmetric visibility like public private(set) and properties in interfaces.

For most of PHP's history, a property was just a slot: reading it returned what was stored, writing it stored whatever you gave it. If you needed validation or a computed value, you made the property private and wrote getName() and setName() methods, and a typical class ended up as 80% boilerplate. PHP 8.4 changed that with two features that work together. Property hooks let a property run code when it's read or written. Asymmetric visibility lets a property be public to read but private (or protected) to write.

With them, you can start with plain public properties, the simplest possible design, and add logic later without changing how anyone uses the class. Code that wrote $user->email = $x keeps working when you add validation to email. This lesson covers get and set hooks, virtual properties, asymmetric visibility, and properties in interfaces and abstract classes.

Both features need PHP 8.4 or newer. You should know classes and properties, constructors and readonly properties first.

The getter and setter problem

Here's the old way of writing a validated property. It works, but look how much code it takes for one value:

PHP
class Product
{
    private string $name;

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): void
    {
        $name = trim($name);
        if ($name === '') {
            throw new InvalidArgumentException('Name cannot be empty');
        }
        $this->name = $name;
    }
}

$product->setName('Desk lamp');
echo $product->getName();

Many classes wrote getters and setters "just in case", because turning a public property into a method later would break every caller. Property hooks remove that reason.

set hooks: running code on write

A hook is a block attached to a property declaration. A set hook runs whenever the property is assigned. Inside it, $value is the incoming value, and $this->name refers to the property's own stored value (its backing value):

PHP Validating a property with a set hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The callers write $lamp->name = ... like they would with any public property, but every assignment, including the one in the constructor, goes through the hook. A failed assignment throws before anything is stored, so the name stays Floor lamp.

A few details:

  • Inside the hook, $this->name reads and writes the backing value directly, without calling the hook again. Anywhere else, $this->name goes through the hook.
  • $value has the property's type by default. You can declare a wider parameter type explicitly, for example set(string|int $value) { ... }, as long as the hook then stores a value of the property's own type.
  • The property type still applies to the stored value, so $lamp->name = 42; with strict_types throws a TypeError before your hook even runs.

The short set form

If the hook just transforms the value, use the arrow form. Whatever the expression returns is stored in the backing value:

PHP
public string $slug {
    set => strtolower(trim($value));
}

That's shorthand for set { $this->slug = strtolower(trim($value)); }.

get hooks: running code on read

A get hook runs when the property is read, and whatever it returns is the property's value. Like set, it has a block form and an arrow form:

PHP get hooks and the short arrow form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

fullName and initials are recalculated on every read, so they always reflect the current first and last names. And trying to write fullName fails with Property Person::$fullName is read-only. Why? Because it's a virtual property.

Virtual and backed properties

PHP decides how to store a hooked property by looking at its hooks:

  • If any hook refers to the property itself ($this->fullName), the property is backed: it has storage, like a normal property, and the hooks wrap that storage.
  • If no hook refers to the property itself, it's virtual: it has no storage at all. Its value exists only while a hook computes it.

A virtual property with only a get hook is read-only, as you just saw. It doesn't appear in var_dump() output, because there's nothing stored to dump. A virtual property can also have a set hook that writes other properties, which gives you two views of the same data:

PHP A virtual property with get and set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Setting fahrenheit to 212 actually stores 100 in celsius. The var_dump() shows only celsius, because fahrenheit has no storage of its own.

Use the block form for a virtual set hook. The arrow form set => expression; always means "store the result in this property", which would turn fahrenheit into a backed property with its own separate value, and the two temperatures would drift apart.

Hooks and arrays

Hooks run when the whole property is read or assigned. They can't see changes made to parts of it, so PHP forbids indirect modification of a backed array property that has a set hook:

PHP
class Post
{
    public array $tags = [] {
        set => array_values(array_unique($value));
    }
}

$post = new Post();
$post->tags = ['php', 'php', 'oop'];  // fine: the hook runs
$post->tags[] = 'web';                 // Error: Indirect modification of Post::$tags is not allowed

To add one element, assign a whole new array ($post->tags = [...$post->tags, 'web'];) or provide a method like addTag().

Asymmetric visibility

Sometimes you don't need any logic; you just want outsiders to read a property but not change it. Before PHP 8.4, that required a private property and a getter, or a readonly property, which also blocks the class itself from changing it later.

Asymmetric visibility (PHP 8.4) lets you give a property a separate visibility for writing. You write the read visibility first, then the write visibility with (set):

PHP public private(set) for a counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Everyone can read balanceCents, but only BankAccount can change it, so deposits must go through deposit(), which enforces the rules. The failed write prints Cannot modify private(set) property BankAccount::$balanceCents from global scope. Unlike readonly, the class can change the property as often as it likes.

The rules:

  • The write visibility must be equal to or stricter than the read visibility. protected public(set) is an error.
  • public private(set) can be shortened to private(set): when only the set visibility is written, the read visibility is public.
  • The property must have a type.
  • private(set) properties are implicitly final, since a child class couldn't write them anyway; use protected(set) if children should be able to write.
  • Asymmetric visibility works with constructor promotion, as the $owner parameter shows.

Remember from the previous lesson that readonly properties are protected(set) by default since 8.4. You can combine them explicitly too: public private(set) readonly string $id is readable everywhere and can be initialized once, only by the class itself.

Hooks or asymmetric visibility?

They solve different problems, and you can combine them on one property:

You want Use
Outsiders can read, only the class can write public private(set)
Validate or normalize every write a set hook
A value computed from other properties a virtual get hook
Set once and never change again readonly

Note that hooked properties can't be readonly (Hooked properties cannot be readonly). If you need validation plus write-once behavior, use private(set) with a set hook and only assign the property in the constructor.

Properties in interfaces

Before PHP 8.4, interfaces could only declare methods, so an interface that wanted "every shape has a name" had to declare getName(). Now an interface can declare a property and say which operations it must support:

PHP Interface properties with get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

{ get; } means "implementers must make this property readable". A plain public property, a readonly promoted property or a virtual get hook all satisfy it, which is what makes interface properties flexible. { set; } requires it to be writable, and { get; set; } requires both.

Abstract classes can declare abstract properties the same way: abstract public string $name { get; }. A child class must then provide the property.

Inheritance and hooks

Child classes can add hooks to an inherited property or override the parent's hooks. Inside an overriding hook, parent::$name::get() and parent::$name::set($value) call the parent's hook (or the plain read/write if the parent had none):

PHP Overriding a hook in a child class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The child lowercases the value and then hands it to the parent's hook, which trims it. You can mark a hook or a whole property final to forbid overriding it.

When to use hooks

Property hooks are powerful, which means they're easy to overuse. Some guidelines:

  • Start with plain public properties (or private(set) ones). Add a hook only when you actually need logic. That's the point of the feature: you can add it later without breaking callers.
  • Keep hooks fast and side-effect free. Reading $order->total should not send an email or run a database query; anyone reading the code expects a property access to be cheap. Expensive work belongs in a method with a name that says what it does.
  • Don't hide surprising behavior. A set hook that validates or normalizes is expected. A set hook that also changes three other properties is a method in disguise.
  • Prefer immutable value objects for values that shouldn't change at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A property has only get => $this->first . " " . $this->last;. What happens when you assign to it from outside?

    The hook never refers to the property itself, so the property is virtual. With no set hook it can only be read, and writing throws "Property ... is read-only".
  2. 2. What does public private(set) int $count = 0; mean?

    The first keyword is the read visibility and private(set) is the write visibility. Unlike readonly, the class can change it as often as it wants.
  3. 3. Inside a set hook for $name, what does $this->name = $value; do?

    Inside its own hooks, a property accesses its backing value directly. Everywhere else, reads and writes go through the hooks.
  4. 4. Which of these is NOT allowed in PHP 8.4?

    Hooked properties can't be readonly. Use private(set) with a set hook if you need validation and write protection.
  5. 5. A backed array property has a set hook. What does $obj->items[] = 'x'; do?

    Hooks see only whole reads and writes, so PHP forbids modifying part of a hooked array. Assign a complete new array or use a method instead.

Summary

  • Property hooks (PHP 8.4) attach code to a property: set { ... } runs on every write with the new value in $value; get => expr or get { ... } runs on every read.
  • Inside its own hooks, $this->prop accesses the stored backing value directly. The short set => expr; stores the expression's result.
  • A property whose hooks never mention it is virtual: no storage, not shown by var_dump(), and read-only if it has no set hook.
  • Hooked array properties can't be modified in place ($obj->tags[] = ...); assign a whole array.
  • Asymmetric visibility (public private(set), protected(set), or just private(set)) makes a property readable widely but writable narrowly, as often as the class needs.
  • Interfaces and abstract classes can declare properties with { get; }, { set; } or both. Hooked properties can't be readonly.
  • Start with plain properties, add hooks only for real logic, and keep them cheap and unsurprising.

Next: Magic Methods