readonly Is Not Immutability
A readonly property only blocks reassignment after construction. It says nothing about the object the property points to. A checkout passes $order to a helper that adds a free sample SKU, and the helper's call changes the same LineItems object that every other holder of $order reads, because $order->items still points at it.
Don't do this:
PHP
<?php
declare(strict_types=1);
namespace App\Cart;
final class LineItems
{
/** @var array<int, string> */
private array $skus = [];
public function add(string $sku): void
{
$this->skus[] = $sku;
}
}
final readonly class Order
{
public function __construct(
public LineItems $items,
) {}
}
$order = new Order(new LineItems());
$order->items->add('SKU-123'); // mutated, even though $items is readonlyDo this instead:
PHP
<?php
declare(strict_types=1);
namespace App\Cart;
final readonly class LineItems
{
/** @param list<string> $skus */
public function __construct(
public array $skus = [],
) {}
public function add(string $sku): self
{
return new self([...$this->skus, $sku]);
}
}
final readonly class Order
{
public function __construct(
public LineItems $items,
) {}
}
$order = new Order(new LineItems());
$updated = new Order($order->items->add('SKU-123'));LineItems now returns a new instance for every change, and PHP refuses to modify its readonly array in place (Cannot indirectly modify readonly property). $order keeps the items it was built with, and $updated holds the new ones. The guarantee only reaches as far as the readonly chain does: a readonly property holding an object is immutable only if that object is too.