Error Identifier: property.readOnly
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 Base
{
public mixed $value;
}
class Child extends Base
{
public readonly mixed $value;
}
Why is it reported? #
A readonly property in a child class is overriding a readwrite property in the parent class. The parent class allows both reading and writing, but the child class restricts writing. This violates the Liskov Substitution Principle because code written against the parent type expects to be able to assign the property.
How to fix it #
Remove the readonly modifier from the child property to match the parent’s readwrite contract:
<?php declare(strict_types = 1);
class Base
{
public mixed $value;
}
class Child extends Base
{
- public readonly mixed $value;
+ public mixed $value;
}
Alternatively, if both should be readonly, add the readonly modifier to the parent property as well:
<?php declare(strict_types = 1);
class Base
{
- public mixed $value;
+ public readonly mixed $value;
}
class Child extends Base
{
public readonly mixed $value;
}
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Properties\OverridingPropertyRule [1]