Error Identifier: unaryPlus.nonNumeric
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(?int $value): void
{
$result = +$value;
}
Why is it reported? #
This error is reported by the phpstan-strict-rules package.
The unary + operator is applied to a non-numeric value. The unary plus operator is intended for numeric types (int, float). When applied to non-numeric types like null, string, or objects, PHP silently coerces the value, which can lead to unexpected results and hides type errors.
How to fix it #
Ensure the operand is a numeric type before applying unary +:
function doFoo(?int $value): void
{
- $result = +$value;
+ if ($value !== null) {
+ $result = +$value;
+ }
}
Or cast the value explicitly if the coercion is intentional:
function doFoo(?int $value): void
{
- $result = +$value;
+ $result = (int) $value;
}
How to ignore this error #
You can use the identifier unaryPlus.nonNumeric to ignore this error using a comment:
// @phpstan-ignore unaryPlus.nonNumeric
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: unaryPlus.nonNumeric
Rules that report this error #
- PHPStan\Rules\Operators\OperandInArithmeticUnaryPlusRule [1] phpstan/phpstan-strict-rules