PHP

PHP 8.4 property hooks and asymmetric visibility in practice

5 min read

Fewer getters, same safety

I have written getTitle() and setTitle() so many times in my life that my fingers type them alone. Most of them do nothing: return the property, assign the property. A few do one useful thing, like trimming a string or refusing an empty value, and for those few we kept all the others, “for consistency”.

PHP 8.4 gives two features that attack exactly this boilerplate: property hooks and asymmetric visibility. My projects run on PHP 8.4 now (the hoja.in project pins config.platform.php to 8.4), so I started using them in real code. Here is what works well, and the one place where I deliberately do not use them. Every snippet below was run on PHP 8.4.

Property hooks: logic on the property itself

A property can now have a set hook and a get hook. The set hook runs on every write, also inside the class. That makes it a good place for validation and normalisation:

<?php

declare(strict_types=1);

final class EventSlug
{
    public string $value {
        set(string $value) {
            $slug = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $value), '-'));
            if ($slug === '') {
                throw new InvalidArgumentException('A slug must not be empty.');
            }
            $this->value = $slug;
        }
    }

    public function __construct(string $value)
    {
        $this->value = $value;
    }
}

$slug = new EventSlug('  TYPO3 Camp Munich 2026! ');
echo $slug->value;              // typo3-camp-munich-2026
$slug->value = 'Hello World';   // still validated: hello-world
new EventSlug('!!!');           // InvalidArgumentException

Inside the hook, $this->value writes the real stored value without calling the hook again. Outside, there is no way around it. Before 8.4 I would have needed a private property plus a getter plus a setter for the same guarantee.

Computed values with a get hook

If a property only has a get hook that never touches its own backing value, it is a virtual property. It uses no memory and cannot be written:

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

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

$speaker = new Speaker('Hoja', 'Latheef');
echo $speaker->fullName;        // Hoja Latheef
$speaker->fullName = 'x';       // Error: Property Speaker::$fullName is read-only

In Fluid this is nice, because {speaker.fullName} just works, there is no getter to name correctly.

Asymmetric visibility: public to read, private to write

The second feature is shorter to explain. public private(set) means everyone can read the property, but only the class itself can write it. For value objects and result objects this replaces the classic “private property plus getter” pair:

final class ImportResult
{
    public private(set) int $created = 0;
    public private(set) array $errors = [];

    public bool $successful {
        get => $this->errors === [];
    }

    public function recordCreated(): void
    {
        $this->created++;
    }

    public function recordError(string $message): void
    {
        $this->errors[] = $message;
    }
}

$result = new ImportResult();
$result->recordCreated();
$result->recordError('Page 25: missing title');

echo $result->created;            // 1
var_dump($result->successful);    // false
$result->created = 99;            // Error: Cannot modify private(set) property
$result->errors[] = 'sneaky';     // Error: Cannot indirectly modify private(set) property

Why not readonly? Because readonly allows exactly one write. A counter that grows during an import needs many writes, but only from inside. That is precisely the gap private(set) closes. And note the last line: appending to the array from outside is blocked too, not only the full assignment.

Where they fit in a TYPO3 extension

Your own PSR-14 events

Events are a sweet spot. Some fields are fixed context, one or two are meant to be changed by listeners, and those often have rules. Hooks work on promoted constructor properties as well:

final class ModifyTeaserLabelEvent
{
    public function __construct(
        public readonly int $contentUid,
        public string $label {
            set(string $value) {
                $value = trim($value);
                if ($value === '') {
                    throw new InvalidArgumentException('The label must not be empty.');
                }
                $this->label = $value;
            }
        },
    ) {}
}

A listener with #[AsEventListener] just writes $event->label = 'Weiterlesen';. The context (contentUid) stays read-only, and an empty label never reaches the template, no matter which extension registered the listener. The same event in PHP 8.3 style needs a getter, a setter with the check, and a private property: three places for one rule.

DTOs and API responses

For data transfer objects that a service fills and a controller or a JSON response reads, public private(set) plus a named constructor is my default now. Fluid, json_encode() and debuggers see public properties, and nobody can change them on the way.

Where I keep classic accessors: Extbase models

For Extbase domain models I stay with protected properties and getters and setters. Not because of style, but because of how Extbase hydrates objects. The DataMapper writes each column through _setProperty(), a method defined in AbstractDomainObject, the parent class of your model. I tested both features against the v14 AbstractEntity:

use TYPO3CMSExtbaseDomainObjectAbstractEntity;

class Event extends AbstractEntity
{
    public private(set) string $title = '';
}

(new Event())->_setProperty('title', 'TYPO3 Camp');
// Error: Cannot modify private(set) property Event::$title from scope Event

private(set) only allows writes from the declaring class, and the write happens in the parent’s method, so hydration fails. protected(set) would pass that check, and a set hook on a protected property does run during _setProperty(). But then your validation runs on every row loaded from the database. Old records that do not follow today’s rule suddenly throw exceptions in a list view. On top of that come lazy loading proxies, ObjectStorage relations and the property mapper for forms, which all have their own expectations about how a model is written. I have not tested all of those paths, and I do not want my first test to be in production. So: models stay classic, validation for forms stays in Extbase validators.

Small things that bit me

  • Arrays with a set hook cannot be modified in place: $bag->items[] = 1 fails with “Indirect modification … is not allowed”. Write a method like addItem().
  • Hooks and readonly do not mix: “Hooked properties cannot be readonly” is a compile error.
  • Interfaces can declare properties, like public string $label { get; }. A class can fulfil that with a plain public property, a readonly one or a hook.
  • Tooling: check that your PHPStan, Rector and IDE versions understand 8.4 syntax before you use it in an extension.
  • Extension support: these are syntax features. An extension that uses them cannot be installed on PHP 8.3 or older, so raise the PHP constraint in composer.json at the same time.

For me, the rule of thumb is simple: new small objects (events, DTOs, value objects, result objects) get hooks and asymmetric visibility; Extbase models keep their accessors. Cheers!

Further reading

Leave a comment

Your email address will not be published.