Jump to the navigation menu

Immutable read-only properties in PHP 8.1

Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:

class AccountDetails {

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

}

This means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable.

Without readonly, a DTO can be created and the property values can be changed:

$accountDetails = new AccountDetails('12345678', '00-00-00');
$accountDetails->accountNumber = 'banana';

With readonly set, you'd get a fatal error instead:

Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in /home/opdavies/tmp/example.php:13

- Oliver

Was this interesting?

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

About me

Picture of Oliver

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