Error Identifier: property.readOnlyDefaultValue
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class Config
{
public readonly string $name = 'default';
}
Why is it reported? #
A readonly property cannot have a default value. PHP does not allow readonly properties to be initialized with a default value in their declaration because a readonly property can only be written once, and that write must happen explicitly (typically in the constructor). Allowing a default value would conflict with the semantics of readonly, which guarantees the property is initialized at a single point in code.
How to fix it #
Move the initialization to the constructor:
<?php declare(strict_types = 1);
class Config
{
- public readonly string $name = 'default';
+ public readonly string $name;
+
+ public function __construct()
+ {
+ $this->name = 'default';
+ }
}
Or use a promoted constructor parameter:
<?php declare(strict_types = 1);
class Config
{
- public readonly string $name = 'default';
-
+ public function __construct(
+ public readonly string $name = 'default',
+ )
+ {
+ }
}
How to ignore this error #
You can use the identifier property.readOnlyDefaultValue to ignore this error using a comment:
// @phpstan-ignore property.readOnlyDefaultValue
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: property.readOnlyDefaultValue
Rules that report this error #
- PHPStan\Rules\Properties\ReadOnlyPropertyRule [1]