Error Identifier: attribute.noConstructor
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);
use Attribute;
#[Attribute]
class MyAttribute
{
}
#[MyAttribute('some value')]
class Foo
{
}
Why is it reported? #
The attribute class does not have a constructor, but it is being instantiated with parameters. When an attribute class has no constructor, it cannot accept any arguments. Passing arguments to an attribute without a constructor will result in an error.
In the example above, MyAttribute has no constructor, so it cannot be used with the argument 'some value'.
How to fix it #
Add a constructor to the attribute class to accept the parameters:
<?php declare(strict_types = 1);
use Attribute;
#[Attribute]
class MyAttribute
{
+ public function __construct(public string $value)
+ {
+ }
}
#[MyAttribute('some value')]
class Foo
{
}
Or remove the arguments from the attribute usage:
<?php declare(strict_types = 1);
-#[MyAttribute('some value')]
+#[MyAttribute]
class Foo
{
}
How to ignore this error #
You can use the identifier attribute.noConstructor to ignore this error using a comment:
// @phpstan-ignore attribute.noConstructor
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.noConstructor
Rules that report this error #
- PHPStan\Rules\Classes\ClassAttributesRule [1]
- PHPStan\Rules\Classes\ClassConstantAttributesRule [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]