Error Identifier: classConstant.type
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 ParentClass
{
/** @var positive-int */
public const VALUE = 1;
}
class ChildClass extends ParentClass
{
/** @var int */
public const VALUE = -1;
}
Why is it reported? #
The type of an overriding class constant is not covariant with the type of the constant in the parent class. When a child class overrides a constant from a parent class, the child’s constant type must be a subtype of (or equal to) the parent’s constant type. This ensures that code relying on the parent’s type contract remains valid.
In the example above, ParentClass::VALUE is typed as positive-int, but ChildClass::VALUE widens the type to int and assigns -1, which violates the parent’s type contract.
How to fix it #
Ensure the overriding constant’s type is a subtype of the parent’s type:
<?php declare(strict_types = 1);
class ChildClass extends ParentClass
{
- /** @var int */
- public const VALUE = -1;
+ /** @var positive-int */
+ public const VALUE = 2;
}
How to ignore this error #
You can use the identifier classConstant.type to ignore this error using a comment:
// @phpstan-ignore classConstant.type
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: classConstant.type
Rules that report this error #
- PHPStan\Rules\Constants\OverridingConstantRule [1]