Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
php

PHP 8.4 private(set): read-only from the outside

People working together at laptops

Every import job I write ends up with a little report object: how many rows were created, how many skipped, which ones blew up. And every time, the same two bad options show up. Either the counters are public and some helper function cheerfully does $report->created = 0 halfway through, or I write three getters and a pile of boilerplate. PHP 8.4's asymmetric visibility removes that trade-off, and I think it is the most underused feature of the release.

The idea: public to read, private to write

As of PHP 8.4 a property can have a separate set visibility, as long as it is not wider than the read visibility. According to the visibility page in the manual, only typed properties qualify, and public private(set) and plain private(set) mean the same thing. Here is the report object:

<?php

declare(strict_types=1);

final class ImportReport
{
    public private(set) int $created = 0;
    public private(set) int $skipped = 0;

    /** @var list<string> */
    public private(set) array $errors = [];

    public function __construct(public readonly string $source)
    {
    }

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

    public function recordSkipped(): void
    {
        $this->skipped++;
    }

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

    public function hasErrors(): bool
    {
        return $this->errors !== [];
    }
}

Callers read $report->created directly, no getter needed. Only the class itself can change it. Note that source is still plain readonly: it is set once in the constructor and never again, which is a different guarantee from "only I may mutate this".

What the compiler now stops

$report = new ImportReport('crm-export.csv');
$report->recordCreated();

echo $report->created;        // 1, reading is public
$report->created = 0;         // Error: cannot modify private(set) property
$report->errors[] = 'oops';   // Error as well, see below

The array case is the one I like most. The manual notes that writing to an array property involves both a get and a set internally, so it follows the more restrictive set visibility. That means the append on the last line fails too. You do not get the old trap where a "protected" collection quietly leaks through a public getter that returns it by reference. The same rule applies to taking a reference to the property, so $x = &$report->created from outside is rejected as well.

Subclasses: private(set) is final

Here is the gotcha I would have hit in a real Drupal service. Per the manual, private(set) implicitly makes the property final, so a child class cannot redeclare it, and cannot write to it either. If you intend subclasses (for example a batch-aware report that also counts retries), use protected(set) instead:

<?php

declare(strict_types=1);

class BaseReport
{
    public protected(set) int $created = 0;
}

final class BatchReport extends BaseReport
{
    public function recordCreated(int $count): void
    {
        $this->created += $count; // allowed: protected(set)
    }
}

Children may also widen the write visibility if they have a reason to, but I would treat that as a code smell.

When I reach for it, and when not

I use it for state holders: reports, progress trackers, accumulators in queue workers and batch callbacks, where the object legitimately changes but only through its own methods. For true value objects I still prefer readonly plus "with" methods that return new instances. One practical note: this needs PHP 8.4, and Drupal 11 sites running 8.3 will get a parse error, so check your composer.json platform requirement before you sprinkle it around a contrib module. I have not run these snippets here, but each rule above is straight from the manual, and I would add one PHPUnit test that asserts the Error on outside writes so a future refactor cannot quietly loosen the visibility.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.