Error Identifier: class.extendsEnum
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);
enum Status
{
case Active;
case Inactive;
}
class MyClass extends Status
{
}
Why is it reported? #
A class cannot extend an enum. Enums in PHP are a special type and do not support inheritance. Attempting to extend an enum will result in a fatal error at runtime.
In the example above, MyClass tries to extend the Status enum, which is not allowed.
How to fix it #
Use the enum directly instead of trying to extend it. If additional functionality is needed, use composition:
<?php declare(strict_types = 1);
-class MyClass extends Status
+class MyClass
{
+ public function __construct(
+ private Status $status,
+ ) {
+ }
}
Or implement an interface if shared behaviour is needed:
<?php declare(strict_types = 1);
interface HasLabel
{
public function label(): string;
}
enum Status: string implements HasLabel
{
case Active = 'active';
case Inactive = 'inactive';
public function label(): string
{
return $this->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\Classes\ExistingClassInClassExtendsRule [1]