oliverdavies.uk/content/node.d421a5a4-8025-4809-8a30-68c723e46af6.yml

97 lines
3.1 KiB
YAML

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: |
<p>Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:</p>
<pre><code class="language-php">class AccountDetails {
public function __construct(
public readonly string $accountNumber,
public readonly string $sortCode,
) {}
}
</code></pre>
<p>This means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable.</p>
<p>Without <code>readonly</code>, a DTO can be created and the property values can be changed:</p>
<pre><code class="language-php">$accountDetails = new AccountDetails('12345678', '00-00-00');
$accountDetails-&gt;accountNumber = 'banana';
</code></pre>
<p>With <code>readonly</code> set, you'd get a fatal error instead:</p>
<blockquote>
<p>Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in /home/opdavies/tmp/example.php:13</p>
</blockquote>
format: full_html
processed: |
<p>Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:</p>
<pre><code class="language-php">class AccountDetails {
public function __construct(
public readonly string $accountNumber,
public readonly string $sortCode,
) {}
}
</code></pre>
<p>This means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable.</p>
<p>Without <code>readonly</code>, a DTO can be created and the property values can be changed:</p>
<pre><code class="language-php">$accountDetails = new AccountDetails('12345678', '00-00-00');
$accountDetails-&gt;accountNumber = 'banana';
</code></pre>
<p>With <code>readonly</code> set, you'd get a fatal error instead:</p>
<blockquote>
<p>Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in /home/opdavies/tmp/example.php:13</p>
</blockquote>
summary: null
field_daily_email_cta: { }