Skip to content

09: Default Values for Readonly Properties

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.

  • 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.

A runnable readonly-defaults.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/09-readonly-defaults/readonly-defaults.php
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";
}
orders.csv
Readonly default already initialized

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.

Change extension to 'tsv' and instantiate two exporters. Verify that they start with the same extension and that reassignment still raises an error.

Continue with Override Attributes on Constants and Enum Cases.