Error Identifier: property.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 MyTrait
{
}
class Foo
{
public MyTrait $bar; // ERROR: Property Foo::$bar has invalid type MyTrait.
}
Why is it reported? #
A trait is being used as a type for a class property. In PHP, traits are not types – they are a mechanism for horizontal code reuse. A trait cannot be used as a type declaration for properties, parameters, or return types. Unlike classes and interfaces, traits do not define a type that objects can be checked against.
How to fix it #
Use an interface or class as the property type instead of a trait:
<?php declare(strict_types = 1);
-trait MyTrait
+interface MyInterface
{
}
class Foo
{
- public MyTrait $bar;
+ public MyInterface $bar;
}
If the trait defines shared behavior, extract an interface that classes using the trait should implement:
<?php declare(strict_types = 1);
+interface HasName
+{
+ public function getName(): string;
+}
+
trait NameTrait
{
public function getName(): string
{
return $this->name;
}
}
class Foo
{
- public NameTrait $entity;
+ public HasName $entity;
}
How to ignore this error #
You can use the identifier property.trait to ignore this error using a comment:
// @phpstan-ignore property.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: property.trait
Rules that report this error #
- PHPStan\Rules\Properties\ExistingClassesInPropertiesRule [1]