orklah / psalm-insane-comparison
检测可能的疯狂比较("字符串" == 0),以帮助迁移到 PHP8
v2.3.0
2024-03-20 21:49 UTC
Requires
- php: ^7.3|^8.0
- ext-simplexml: *
- vimeo/psalm: ^4|^5|dev-master
Requires (Dev)
- nikic/php-parser: ^4.0|^5
README
一个检测在引入 PHP RFC: 更合理的字符串与数字比较 后代码行为可能改变的 Psalm 插件
安装
$ composer require --dev orklah/psalm-insane-comparison $ vendor/bin/psalm-plugin enable orklah/psalm-insane-comparison
用法
运行您通常的 Psalm 命令
$ vendor/bin/psalm
解释
在 PHP8 之前,非空字符串与字面量 int 0 的比较结果为 true
。但在 PHP RFC: 更合理的字符串与数字比较 之后,情况不再如此。
$a = 'banana'; $b = 0; if($a == $b){ echo 'PHP 7 will display this'; } else{ echo 'PHP 8 will display this instead'; }
此插件有助于识别这些情况,以便在迁移之前进行检查。
您可以通过多种方式解决这个问题
- 使用严格等于
$a = 'banana'; $b = 0; if($a === $b){ echo 'This is impossible'; } else{ echo 'PHP 7 and 8 will both display this'; }
- 使用类型转换使两个操作数具有相同的类型
$a = 'banana'; $b = 0; if((int)$a == $b){ echo 'PHP 7 and 8 will both display this'; } else{ echo 'This is impossible'; }
$a = 'banana'; $b = 0; if($a == (string)$b){ echo 'This is impossible'; } else{ echo 'PHP 7 and 8 will both display this'; }
- 让 Psalm 理解当整型操作数不是字面量时,您正在处理正整数
$a = 'banana'; /** @var positive-int $b */ if($a == $b){ echo 'This is impossible'; } else{ echo 'PHP 7 and 8 will both display this'; }
- 让 Psalm 理解当字符串操作数不是字面量时,您正在处理数字字符串
/** @var numeric-string $a */ $b = 0; if($a == $b){ echo 'PHP 7 and 8 will both display this depending on the value of $a'; } else{ echo 'PHP 7 and 8 will both display this depending on the value of $a'; }