Error Identifier: property.readWrite
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 readonly string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
class Child extends Base
{
public string $name; // ERROR: Readwrite property Child::$name overrides readonly property Base::$name.
public function __construct(string $name)
{
$this->name = $name;
}
}
Why is it reported? #
A child class declares a readwrite (non-readonly) property that overrides a readonly property from the parent class. This violates the contract established by the parent class – the parent guarantees that the property cannot be modified after initialization, but the child removes this guarantee. This breaks the Liskov Substitution Principle because code relying on the parent type expects the property to be immutable.
How to fix it #
Keep the readonly modifier on the overriding property:
<?php declare(strict_types = 1);
class Child extends Base
{
- public string $name;
+ public readonly string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
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]