Error Identifier: outOfClass.parent
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 parent::FOO; // ERROR: Using parent outside of class scope.
Why is it reported? #
The keyword parent refers to the parent class of the class in which it is used. It can only appear inside a class definition that extends another class. Using parent outside of a class scope (for example, in a function or in the global scope) is a PHP error because there is no class context to resolve the parent from.
This error is reported in various contexts: accessing constants (parent::FOO), calling static methods (parent::method()), accessing static properties (parent::$prop), using new parent(), or using parent in an instanceof check.
How to fix it #
Use the fully qualified class name instead of parent when outside a class:
<?php declare(strict_types = 1);
-echo parent::FOO;
+echo BaseClass::FOO;
Or move the code inside a class method where parent is valid:
<?php declare(strict_types = 1);
class BaseClass
{
public const FOO = 'bar';
}
class ChildClass extends BaseClass
{
public function doFoo(): void
{
echo parent::FOO; // This works inside a class that extends another
}
}
How to ignore this error #
You can use the identifier outOfClass.parent to ignore this error using a comment:
// @phpstan-ignore outOfClass.parent
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: outOfClass.parent
Rules that report this error #
- PHPStan\Rules\Classes\ClassConstantRule [1]
- PHPStan\Rules\Classes\ExistingClassInInstanceOfRule [1]
- PHPStan\Rules\Classes\InstantiationRule [1]
- PHPStan\Rules\Methods\CallStaticMethodsRule [1]
- PHPStan\Rules\Methods\StaticMethodCallableRule [1]
- PHPStan\Rules\Properties\AccessStaticPropertiesInAssignRule [1]
- PHPStan\Rules\Properties\AccessStaticPropertiesRule [1]