Error Identifier: class.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 Nonreadonly
{
}
readonly class Foo extends Nonreadonly
{
}
Why is it reported? #
A readonly class can only extend another readonly class, and a non-readonly class cannot extend a readonly class. PHP enforces this constraint to maintain consistency of the readonly invariant across the inheritance chain. When a class is declared as readonly, all its properties are implicitly readonly, and this guarantee must hold for parent classes as well.
In the example above, the readonly class Foo extends the non-readonly class Nonreadonly, which violates this rule.
How to fix it #
Make the parent class readonly as well:
<?php declare(strict_types = 1);
-class Nonreadonly
+readonly class Nonreadonly
{
}
readonly class Foo extends Nonreadonly
{
}
Or remove the readonly modifier from the child class:
<?php declare(strict_types = 1);
class Nonreadonly
{
}
-readonly class Foo extends Nonreadonly
+class Foo extends Nonreadonly
{
}
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\Classes\ExistingClassInClassExtendsRule [1]