Error Identifier: magicConstant.outOfTrait
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);
class Foo
{
public function getTraitName(): string
{
return __TRAIT__;
}
}
Why is it reported? #
The magic constant __TRAIT__ returns the name of the trait where it is used. When used outside of a trait, it always returns an empty string. This is almost certainly a mistake, as the developer likely intended to use this constant inside a trait, or meant to use a different magic constant like __CLASS__.
How to fix it #
Move the usage of __TRAIT__ inside a trait, or use a different magic constant that is appropriate for the context.
<?php declare(strict_types = 1);
-class Foo
+trait Foo
{
public function getTraitName(): string
{
return __TRAIT__;
}
}
Alternatively, if you meant to get the class name:
<?php declare(strict_types = 1);
class Foo
{
- public function getTraitName(): string
+ public function getClassName(): string
{
- return __TRAIT__;
+ return __CLASS__;
}
}
How to ignore this error #
You can use the identifier magicConstant.outOfTrait to ignore this error using a comment:
// @phpstan-ignore magicConstant.outOfTrait
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: magicConstant.outOfTrait
Rules that report this error #
- PHPStan\Rules\Constants\MagicConstantContextRule [1]