Error Identifier: magicConstant.outOfClass
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);
echo __CLASS__;
Why is it reported? #
The magic constant __CLASS__ is used outside of a class definition, where it always evaluates to an empty string ''. This is almost never the intended behaviour and usually indicates that the code was moved out of a class without updating the constant reference.
How to fix it #
Move the code inside a class, or use a different way to get the class name:
-echo __CLASS__;
+class Foo
+{
+ public function printName(): void
+ {
+ echo __CLASS__; // outputs "Foo"
+ }
+}
If the code is in a function and needs the caller’s class name, accept it as a parameter:
-function logContext(): void
+function logContext(string $className): void
{
- echo __CLASS__;
+ echo $className;
}
How to ignore this error #
You can use the identifier magicConstant.outOfClass to ignore this error using a comment:
// @phpstan-ignore magicConstant.outOfClass
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.outOfClass
Rules that report this error #
- PHPStan\Rules\Constants\MagicConstantContextRule [1]