Skip to content

PHP 8.1 Readonly property cannot have a default value #5906

@sofyco

Description

@sofyco

Bug report

PHPStan with PHP 8.1 shows an error when you use the default value for a read-only property in the constructor.

https://wiki.php.net/rfc/readonly_properties_v2

As the property has no default value, the assignment in the constructor is initializing, and thus legal. The constructor property promotion feature was specifically designed for forward-compatibility with readonly properties.

Code snippet that reproduces the problem

final class ErrorResponse
{
    public function __construct(public readonly string $message, public readonly array $parameters = [])
    {
    }
}

has error:

Readonly property cannot have a default value.

Expected output

No errors should be detected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions