uuid: - value: d421a5a4-8025-4809-8a30-68c723e46af6 langcode: - value: en type: - target_id: daily_email target_type: node_type target_uuid: 8bde1f2f-eef9-4f2d-ae9c-96921f8193d7 revision_timestamp: - value: '2025-05-11T09:00:44+00:00' revision_uid: - target_type: user target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849 revision_log: { } status: - value: true uid: - target_type: user target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849 title: - value: | Immutable read-only properties in PHP 8.1 created: - value: '2023-04-13T00:00:00+00:00' changed: - value: '2025-05-11T09:00:44+00:00' promote: - value: false sticky: - value: false default_langcode: - value: true revision_translation_affected: - value: true path: - alias: /daily/2023/04/13/immutable-read-only-properties-in-php-8-1 langcode: en body: - value: |

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

format: full_html processed: |

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

summary: null field_daily_email_cta: { }