Error Identifier: ternary.shortNotAllowed
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);
$value = $input ?: 'default';
Why is it reported? #
This error is reported by phpstan-strict-rules.
The short ternary operator (?:) is being used. The short ternary returns the left operand if it is truthy, or the right operand otherwise. This is problematic because it relies on PHP’s loose truthiness rules, which can lead to unexpected behavior. For example, 0 ?: 'default' returns 'default' even though 0 is a valid value.
How to fix it #
If checking for null, use the null coalescing operator (??) which only checks for null without evaluating truthiness:
-$value = $input ?: 'default';
+$value = $input ?? 'default';
If an explicit condition is needed, use the full ternary operator:
-$value = $input ?: 'default';
+$value = $input !== '' ? $input : 'default';
How to ignore this error #
You can use the identifier ternary.shortNotAllowed to ignore this error using a comment:
// @phpstan-ignore ternary.shortNotAllowed
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: ternary.shortNotAllowed
Rules that report this error #
- PHPStan\Rules\DisallowedConstructs\DisallowedShortTernaryRule [1] phpstan/phpstan-strict-rules