Signatur
public readonly string $name; // PHP 8.1+
final readonly class Money {} // PHP 8.2+
Beschreibung
Der beste Weg zu Value Objects und DTOs. Der Compiler garantiert, dass niemand die Werte nach der Konstruktion ändern kann.
Rückgabewert
Typ
void
Beispiele
Readonly-Klasse
<?php
final readonly class Money {
public function __construct(
public int $cents,
public string $currency,
) {}
public function plus(Money $other): Money {
return new Money($this->cents + $other->cents, $this->currency);
}
}
// Wichtig · Fallstricke
Ab PHP 8.4 gibt es „asymmetric visibility" — Properties können public zum Lesen und private zum Schreiben sein: public private(set) string $name.