ImpossibleTypeComparison
error native on by defaultGroup: Probable bugs
Report a strict comparison (===, !==) whose operands can never be identical, because the code itself shows they have no value in common: an int against a string, an object against a scalar, two classes no object can belong to at once, two locals holding different literals. Also report a loose comparison (==, !=, <>) that PHP 8's conversions can never make true, such as objects of two unrelated classes or an array against a number. Such a comparison always gives the same answer, so the branch it guards is dead or always taken. Types that come only from PHPDoc never count.
Example
<?php
final class Order {}
final class Refund {}
function compare(int $qty, string $code, Order $order, Refund $refund, bool $bulk): void {
if ($qty === $code) {
return;
}
$same = $order === $refund;
$mode = 'cart';
if ($bulk) {
$mode = 'bulk';
}
$sale = $mode === 'sale';
$loose = $order == $refund;
}Reported:
- line 5: This comparison is always false: int and string share no value.
- line 8: This comparison is always false: Order and Refund share no value.
- line 13: This comparison is always false: 'bulk'|'cart' and 'sale' share no value.
- line 14: This comparison is always false: Order and Refund never compare equal.
Detection
A
===,!==,==,!=or<>comparison. Neither operand is thenullliteral (RedundantTypeCheck judges the strict ones), and not both are literals.Each operand's type comes from native declarations only (typed parameters, properties and returns, literals, operations, the types PHP's own functions declare), narrowed by the conditions guarding the comparison, as for PossiblyNullAccess. The type must also be decided the same way with PHPDoc taken into account, and with the newest supported PHP version as target.
No value of one type is identical to a value of the other. Scalar types,
null, arrays and objects never meet each other;intnever meetsfloat;truenever meetsfalse. Two classes meet unless one can never be the other: unrelated classes (single inheritance), or a final class (or enum) outside the other's subtypes.callable,iterableandobjectmay meet the values they can hold.Exact values tell two operands of the same type apart only when both are literals, or locals whose every reaching value is a literal assigned in the same function (
$mode = 'cart'; if ($bulk) { $mode = 'bulk'; }never equals'sale'). Integer ranges and string lengths never do.D5. A loose comparison is reported only when every pair of values of the two types is one PHP 8 always finds unequal, whatever the values (exact values never decide it):
Left Right Why never equal plain object plain object of a class no object of the first can be objects of different classes are unequal plain object array, null,falsean object converts to no array, and to truearray int,float,stringan array only equals an array, or nulland aboolby truthinesstruefalse,nullboth sides compare as booleans A plain object is an instance of a class or an enum (not an interface, which an object of any class may implement) whose hierarchy is wholly known, no dependency declares (E5), and that extends no class of PHP itself:
DateTimeequals aDateTimeImmutableat the same instant, an emptySimpleXMLElementequalsfalse, aGMPnumber equals anint.Every other pair may be equal and keeps the comparison silent: an object against an
intor afloat(it converts to 1, with a notice),true, or astring(through__toString());nullagainstfalse,0,0.0,''or[]; an array against abool; a number against a numeric string (1 == '01'), anintagainst afloat;object,iterableandcallablevalues against anything.
Exceptions (no report)
- An operand whose type is unknown, includes
mixed, or is an intersection; an unreachable comparison. - An operand that reads a constant (global or class constant, or an element of one), whose value may depend on configuration;
$thisinside a closure or an arrow function, which may run bound to another object. - An operand written again later in a loop around the comparison (assigned, incremented, iterated into, destructured into, unset), itself or a value it reads through: its type may change from one iteration to the next.
- An operand that is, or a local assigned, a call to a PHP function or method whose declared return type changes after the target PHP version (
sort()returnsboolbefore PHP 8.2 andtrueafter). - E5. Classes whose hierarchy is not wholly known, traits, and classes that are or extend a class declared in the project's vendor directory (Composer's
config.vendor-dir,vendorby default): another release of that package, which the project may also support, may relate them differently. A directory namedvendorelsewhere holds project code. - Code in a test context (a file ending with
Test.php,Spec.phpor.phpt, aFixturesdirectory, or a test class), and comparisons inside anassert()call. - Loose comparisons outside the pairs of D5, which convert their operands.
- Comparisons other rules report, when they run and check that code: in the condition of an
iforelseifthat is an&&chain (one symbolic operator), a comparison of the value the firstinstanceofof the chain tests with a literal, also under prefix operators (-1,!false), unless loose against a string when that class has__toString()(NotOptimalIfConditions, when it reportsinstanceofflaws); a call toarray_search()compared withtrue, unless the call is in parentheses (ArraySearchUsedAsInArray);xml_parse()compared withfalse, also through a local (XmlParseZeroComparedWithFalse); a call to thecompare()method ofCollator(or of a subclass) tested equal totrue(CollatorComparisonTruthinessReversed). The function formcollator_compare(), a collation result held in a local and a test that it is not identical totruestay this rule's.
Fix
None: the comparison reveals a wrong assumption, which only the author can correct.
PHP versions
No gating.
Configure
In custos.json:
{
"rules": {
"ImpossibleTypeComparison": {
"enabled": false
}
}
}Suppress
Before the statement or declaration (or the first statement of the file):
// @custos-ignore ImpossibleTypeComparison