Error Identifier: attribute.abstract
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);
#[\Attribute]
abstract class MyAttribute
{
public function __construct(public string $value)
{
}
}
#[MyAttribute('test')]
class Foo
{
}
Why is it reported? #
PHP requires attribute classes to be non-abstract classes. An abstract class cannot be used as an attribute because PHP needs to instantiate the attribute when it is applied, and abstract classes cannot be instantiated. Declaring an abstract class with #[\Attribute] or using it as an attribute is invalid and will cause a runtime error.
In the example above, MyAttribute is declared as an abstract class with the #[\Attribute] attribute, which is not allowed.
How to fix it #
Remove the abstract keyword from the attribute class:
<?php declare(strict_types = 1);
#[\Attribute]
-abstract class MyAttribute
+class MyAttribute
{
public function __construct(public string $value)
{
}
}
#[MyAttribute('test')]
class Foo
{
}
If the class needs to share behavior with other attribute classes, use composition or a trait instead of inheritance from an abstract class.
How to ignore this error #
You can use the identifier attribute.abstract to ignore this error using a comment:
// @phpstan-ignore attribute.abstract
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: attribute.abstract
Rules that report this error #
- PHPStan\Rules\Classes\ClassAttributesRule [1]
- PHPStan\Rules\Classes\ClassConstantAttributesRule [1]
- PHPStan\Rules\Classes\NonClassAttributeClassRule [1]
- PHPStan\Rules\Constants\ConstantAttributesRule [1]
- PHPStan\Rules\EnumCases\EnumCaseAttributesRule [1]
- PHPStan\Rules\Functions\ArrowFunctionAttributesRule [1]
- PHPStan\Rules\Functions\ClosureAttributesRule [1]
- PHPStan\Rules\Functions\FunctionAttributesRule [1]
- PHPStan\Rules\Functions\ParamAttributesRule [1]
- PHPStan\Rules\Methods\MethodAttributesRule [1]
- PHPStan\Rules\Properties\PropertyAttributesRule [1]
- PHPStan\Rules\Properties\PropertyHookAttributesRule [1]
- PHPStan\Rules\Traits\TraitAttributesRule [1]