- Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework
- Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
PHP 8.4 shipped asymmetric visibility in November 2024, and most teams that picked it up used it for exactly one thing: skipping the getter. That's the obvious case. There are four better ones.
The feature is small. The syntax is public public(set), public protected(set), public private(set) and the symmetric variants. The read modifier sits where it always did. The write modifier goes in parentheses next to set. That's the whole thing.
What it replaces is bigger. It replaces the private-property-plus-public-getter pattern PHP teams have written for fifteen years. It replaces a chunk of constructor boilerplate. Paired with property hooks and readonly, it replaces the inner builder pattern. Let's go through it.
What public(set) actually changes
Here's an Order class in PHP 8.3. Status changes from inside the domain, total changes after items are recalculated, but both fields are read from anywhere: templates, serializers, controllers.
// PHP 8.3, the old way
final class Order
{
private OrderStatus $status;
private Money $total;
public function __construct(
private readonly OrderId $id,
OrderStatus $status,
Money $total,
) {
$this->status = $status;
$this->total = $total;
}
public function getId(): OrderId
{
return $this->id;
}
public function getStatus(): OrderStatus
{
return $this->status;
}
public function getTotal(): Money
{
return $this->total;
}
public function markPaid(): void
{
$this->status = OrderStatus::Paid;
}
}
Three getters that do nothing. A constructor that exists only to assign. The same shape in PHP 8.4:
// PHP 8.4, same semantics, one third the code
final class Order
{
public function __construct(
public readonly OrderId $id,
public private(set) OrderStatus $status,
public private(set) Money $total,
) {}
public function markPaid(): void
{
$this->status = OrderStatus::Paid;
}
}
The read surface is unchanged. $order->status works from a Twig template the same way $order->getStatus() did. The write surface is now scoped to the class itself. A controller cannot do $order->status = OrderStatus::Refunded. It'll get Cannot modify private(set) property Order::$status from global scope.
That's the headline. Now the patterns.
Pattern 1: Read-anywhere, write-from-domain
This is the obvious case, and the one most blog posts stop at. You want a property that any caller can read but only the owning aggregate can mutate. Before 8.4, you wrote a getter and a private field. Now you write the field once.
final class EmailAddress
{
public public(set) string $value {
set (string $value) {
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
"Invalid email: {$value}"
);
}
$this->value = strtolower($value);
}
}
public function __construct(string $value)
{
$this->value = $value;
}
}
public public(set) is the loud one: readable and writable from everywhere. Pair it with a property hook (the other big PHP 8.4 feature) and you get validation on every assignment, including the one inside the constructor. That EmailAddress class is now a value object with five lines of business logic and zero getter-setter ceremony.
Worth noting: the hook fires on the constructor assignment too. If you ever want to bypass it, you can't from inside the constructor without changing the property declaration. That's a feature, not a bug. Your invariants hold from the moment the object exists.
Pattern 2: Builder objects without the builder
The builder pattern in PHP got cleaned up by readonly in 8.2 and by clone-with semantics in 8.4. Asymmetric visibility is the last piece. You can write a fluent immutable object without a separate OrderBuilder class.
final class Order
{
public function __construct(
public readonly OrderId $id,
public private(set) OrderStatus $status = OrderStatus::Draft,
public private(set) ?Address $shippingAddress = null,
public private(set) array $items = [],
) {}
public function withShippingAddress(Address $address): self
{
$clone = clone $this;
$clone->shippingAddress = $address;
return $clone;
}
public function withItem(OrderItem $item): self
{
$clone = clone $this;
$clone->items = [...$this->items, $item];
return $clone;
}
}
private(set) means the property is writable from inside the class, including from inside a clone of the class. So $clone->shippingAddress = $address works because we're still inside Order when we run it. Outside callers can read every field. Outside callers cannot mutate.
This is the part that makes builder classes obsolete for most cases. The builder existed to hold the half-built state separately from the final object. With clone-on-write and private(set), you can hold both states in the same class without leaking mutability to the world.
Pattern 3: Aggregate-root field guards
In domain-driven design you've got aggregate roots that own a chunk of state and enforce invariants over it. The Order owns its line items. Nobody outside the aggregate gets to mess with the items array directly. Before 8.4, this meant private array $items plus public function getItems(): array { return $this->items; } plus a defensive copy if you cared about callers mutating the returned array.
Asymmetric visibility plus a property hook makes the guard explicit and short:
final class Order
{
public function __construct(
public readonly OrderId $id,
public private(set) Money $total = new Money(0, 'EUR'),
public private(set) array $items = [],
) {}
public function addItem(OrderItem $item): void
{
if ($this->status !== OrderStatus::Draft) {
throw new DomainException(
"Cannot add items to a {$this->status->value} order"
);
}
$this->items[] = $item;
$this->recalculateTotal();
}
private function recalculateTotal(): void
{
$this->total = array_reduce(
$this->items,
fn(Money $sum, OrderItem $i) => $sum->add($i->subtotal()),
new Money(0, 'EUR'),
);
}
public public(set) OrderStatus $status = OrderStatus::Draft {
set (OrderStatus $next) {
if (!$this->status->canTransitionTo($next)) {
throw new DomainException(
"Cannot move from {$this->status->value} to {$next->value}"
);
}
$this->status = $next;
}
}
}
Two things to notice. First, $this->items[]= $item works from inside addItem() because we're inside the class. Second, the status property uses public public(set) plus a hook, meaning anyone can assign to it, but the hook runs the transition guard. That's the right shape when you want external callers to drive transitions (a workflow engine, a controller after authorization) but you still want the domain to reject illegal moves.
The combination of public(set) plus property hook is asymmetric visibility's best partner.
Pattern 4: DTO inputs with selective immutability
DTOs are the case where people overuse readonly class and then can't deserialize them. You want most fields locked after construction. You want one or two to be settable by infrastructure (a request ID set by middleware, a correlation ID injected by an event bus). Asymmetric visibility maps to this perfectly.
final class CreateOrderCommand
{
public function __construct(
public readonly CustomerId $customerId,
public readonly array $items,
public readonly Address $shippingAddress,
public public(set) ?string $correlationId = null,
public public(set) ?string $idempotencyKey = null,
) {}
}
Three fields are truly immutable. Two fields are open for write. Anyone can set them, but the values flow from infrastructure, not the user. The command is still a value-ish object. The framework can inject what it needs without you writing a setter.
public(set) on the open fields means no scoping rules. If you want to lock them to a specific layer, switch to protected(set) and require the framework integration to extend the DTO. I'd avoid that. It's clever, and clever is a smell in DTOs.
Pattern 5: Where it breaks: serialization, Eloquent casting, Doctrine hydration
The pattern is great. The infrastructure around it isn't, yet.
Symfony Serializer (6.4 and 7.x) handles asymmetric visibility correctly for deserialization because it uses reflection and respects property scope when writing. So $serializer->deserialize($json, Order::class, 'json') works fine, because the serializer is privileged enough to write private(set) fields. Newer point releases handle it cleanly.
Eloquent attribute casting (Laravel 11.x and 12.x) is the case that bites integration code. Eloquent assigns properties via __set() on the model, not on the value object. If you've got a custom cast that produces an asymmetric-visibility value object, the cast itself works. But if you write the cast's set() method to mutate an existing instance, you'll hit Cannot modify private(set) property. The fix is to always return a new instance from CastsAttributes::set(), never mutate. That's good practice anyway; PHP 8.4 just makes you do it.
Doctrine ORM (3.x) hydrates entities via reflection, so private and private(set) properties hydrate fine. The trap is Doctrine's change-tracking. When you mutate a tracked entity via a method, Doctrine sees the change. When you clone it (Pattern 2 above), Doctrine treats the clone as detached. Don't mix the clone-with-readonly pattern with Doctrine-managed entities; the framework expects mutability on its managed objects.
JMS Serializer (still common in Symfony shops) had no support at 3.31. It assigns through public scope, which breaks private(set). Either upgrade to Symfony Serializer or write a custom handler.
The gotcha: protected(set) plus inheritance plus constructor promotion
This is the one undocumented edge case. Constructor-promoted properties with protected(set) look fine at definition. They get weird at extension.
class Money
{
public function __construct(
public protected(set) int $amount,
public readonly string $currency,
) {}
}
class TaxableMoney extends Money
{
public function withTax(float $rate): self
{
$clone = clone $this;
$clone->amount = (int) ($this->amount * (1 + $rate));
return $clone;
}
}
That works. The child class is inside the protected(set) scope so the assignment is legal. The catch: if a third-party library extends your class and tries to mutate amount through a method on its own subclass, it'll work too. protected(set) is wider than people assume. It's the equivalent of writing a protected function setAmount() in 8.3, which means any subclass anywhere is part of your write surface.
If you want true immutability after construction, use public private(set). If you want a hierarchy where children mutate, use public protected(set) and document that the subclass tree is part of your write contract.
When NOT to use it
Not every short-lived object needs asymmetric visibility. A request DTO that lives for one HTTP call, gets validated, gets handed to a use case, and gets garbage-collected doesn't need private(set). The cognitive cost of the modifier is real. The runtime cost is zero, but the cost of someone reading your code and wondering why you bothered isn't.
The shape I'd recommend:
- Aggregate roots and entities with invariants: yes.
- Value objects that ship across boundaries: yes, paired with
readonlyor with hooks. - Internal DTOs that live for one request: no,
public readonlyor plainpublicis enough. - Library code with a public API: yes, for any field where the contract is "callers read, library writes."
- Models managed by an ORM: only with the caveats above.
PHP 8.4's asymmetric visibility isn't a revolution. It's the missing piece that lets you stop writing getter classes and start writing real objects. Five-year-old codebases full of private $foo plus public function getFoo() are exactly the codebases that should run Rector against the relevant rule and reclaim a thousand lines of nothing.
Which of these five patterns is the first one you'd reach for in your codebase, and which property would you rewrite first?
If this was useful
Asymmetric visibility is the kind of language feature that nudges you toward smaller, more honest objects, the kind of objects that survive a framework swap. That's the architectural layer the book covers: how to build PHP applications that outlive Laravel, Symfony, or whichever framework you're on this year. If the patterns in this post resonated, Decoupled PHP is the longer-form version, with chapters on aggregates, value objects, and the boundary between domain code and framework code.
Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.

Top comments (0)