Error Identifier: pow.leftNonNumeric
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);
function doFoo(): void
{
$null = null;
$result = $null ** 2;
}
Why is it reported? #
The exponentiation operator (**) is intended for numeric arithmetic. When a non-numeric value such as null, an object, or a non-numeric string is used on the left side of the ** operator, PHP will attempt implicit type coercion, which is error-prone and usually indicates a bug.
In the example above, null is used as the base of the exponentiation, which PHP silently coerces to 0.
This rule is provided by the phpstan-strict-rules package.
How to fix it #
Ensure the left operand is a numeric type (int, float, or numeric string):
<?php declare(strict_types = 1);
-function doFoo(): void
+function doFoo(int $base): void
{
- $null = null;
- $result = $null ** 2;
+ $result = $base ** 2;
}
Or handle the possibly-null value explicitly:
<?php declare(strict_types = 1);
function doFoo(?int $base): void
{
- $result = $base ** 2;
+ $result = ($base ?? 0) ** 2;
}
How to ignore this error #
You can use the identifier pow.leftNonNumeric to ignore this error using a comment:
// @phpstan-ignore pow.leftNonNumeric
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: pow.leftNonNumeric
Rules that report this error #
- PHPStan\Rules\Operators\OperandsInArithmeticExponentiationRule [1] phpstan/phpstan-strict-rules