Error Identifier: varTag.trait
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);
trait FooTrait
{
}
class Foo
{
public function doFoo(): void
{
/** @var FooTrait $test */
$test = new self();
}
}
Why is it reported? #
The @var PHPDoc tag references a trait as a type. Traits cannot be used as types in PHP because they are not instantiable and cannot be used in instanceof checks or type declarations. A variable cannot hold a value “of type trait” – traits are only used via the use keyword inside classes.
How to fix it #
Use an interface or a class instead of a trait in the @var tag:
<?php declare(strict_types = 1);
+interface FooInterface
+{
+}
+
trait FooTrait
{
}
class Foo
{
public function doFoo(): void
{
- /** @var FooTrait $test */
+ /** @var FooInterface $test */
$test = new self();
}
}
Or use the concrete class type that uses the trait:
<?php declare(strict_types = 1);
class Foo
{
use FooTrait;
public function doFoo(): void
{
- /** @var FooTrait $test */
+ /** @var Foo $test */
$test = new self();
}
}
How to ignore this error #
You can use the identifier varTag.trait to ignore this error using a comment:
// @phpstan-ignore varTag.trait
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: varTag.trait
Rules that report this error #
- PHPStan\Rules\PhpDoc\InvalidPhpDocVarTagTypeRule [1]