Source: stitcher.io

Readonly classes in PHP 8.2
PHP 8.2 adds a new way of declaring classes: you can make them readonly. In practice, it means that all properties of that class will be readonly.

In other words, instead of writing this: class BlogData { public function __construct( public readonly string $title, public readonly Status $status, public readonly ?DateTimeImmutable $publishedAt = null, ) {}}

I've written about readonly properties before, so let's quickly summarise first: readonly properties can only be written once — usually in the constructor; only typed properties can be made readonly; they cannot have a default value (unless you're using promoted properties); the readonly flag cannot be changed during inheritance; and finally you cannot unset readonly properties. Since readonly classes are merely syntactic sugar for making all properties of that class readonly, it means that the same rules apply to readonly classes as well: all properties of a readonly class can only be written once, and can not be unset; a readonly class can only have typed properties; properties of a readonly class can not have a default value unless you're using promoted properties; and you cannot change the readonly class flag during inheritance.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners