Refactoring with readonly classes in PHP 8.2

Marian Kostadinov (stochnagara on Twitter) replied to Friday's email about DTOs and value objects to tell me about readonly classes, which can be done in PHP 8.2.

Looking at the previous class:

class AccountDetails {

  public function __construct(
    public readonly string $accountNumber,
    public readonly string $sortCode,
  ) {}

}

Instead of setting each property as readonly, the whole class can instead be marked as readonly:

readonly class AccountDetails {

  public function __construct(
    public string $accountNumber,
    public string $sortCode,
  ) {}

}

Thanks for the suggestion, Marian!

- Oliver

P.S. Are you still using Drupal 7 and don’t know what’s involved to upgrade to Drupal 10? Book a Drupal 7 upgrade consultation call or an upgrade roadmap.

Was this useful?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.