Skip to main content

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!

Was this interesting?

Subscribe to my daily newsletter for software professionals on software development and delivery, Drupal, DevOps, community, and open-source.

About me

Picture of Oliver

I'm a certified Drupal Triple Expert and former Drupal Association staff member with 18 years of experience, a Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.