orklah/psalm-insane-comparison

检测可能的疯狂比较("字符串" == 0),以帮助迁移到 PHP8

安装量: 1,084,229

依赖项: 3

建议者: 0

安全性: 0

星标: 34

关注者: 4

分支: 4

开放问题: 0

类型:psalm-plugin

v2.3.0 2024-03-20 21:49 UTC

This package is auto-updated.

Last update: 2024-09-20 22:53:28 UTC


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';
}