Use Anonymous Readonly Classes in PHP 8.3

Use Anonymous Readonly Classes in PHP 8.3

The readonly classes were introduced in PHP 8.2. This means that all class properties are set to readonly, allowing them to be initialized once but preventing any later modifications. Since PHP 8.3, anonymous classes may now be marked as readonly as well.

Consider the following code snippet:

<?php

$logger = new readonly class() {
    private string $fileName;

    public function setFileName(string $fileName): void
    {
        $this->fileName = $fileName;
    }
};

$logger->setFileName('test.log'); // OK
$logger->setFileName('prod.log'); // Error

In the provided code, a readonly anonymous class is instantiated as $logger, featuring a private property $fileName. The setFileName method allows setting the file name. However, attempting to call setFileName a second time with a different value, such as prod.log, results in a fatal error. This error arises from the readonly nature of the class, preventing modifications to the fileName property after it has been initially set.

Leave a Comment

Cancel reply

Your email address will not be published.