09: Default Values for Readonly Properties
Overview
Section titled “Overview”Define a fixed export format in a readonly class. A property default can satisfy a get-only interface property as soon as the object is created.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable readonly-defaults.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/09-readonly-defaults/readonly-defaults.php<?php
declare(strict_types=1);
interface ExportFormat{ public string $extension { get; }}
final readonly class CsvFormat implements ExportFormat{ public string $extension = 'csv';
public function filename(string $base): string { return $base . '.' . $this->extension; }}
$format = new CsvFormat();echo $format->filename('orders'), PHP_EOL;
try { $format->extension = 'tsv';} catch (Error) { echo "Readonly default already initialized\n";}Expected Result
Section titled “Expected Result”orders.csvReadonly default already initializedWhy It Works
Section titled “Why It Works”A declared default initializes the property before the constructor runs. If callers need to supply a value, use a constructor parameter. A promoted parameter’s default applies to that parameter and property initialization occurs through promotion.
Exercise
Section titled “Exercise”Change extension to 'tsv' and instantiate two exporters. Verify that they start with the same extension and that reassignment still raises an error.
Wrap-up
Section titled “Wrap-up”Continue with Override Attributes on Constants and Enum Cases.