PHP: list() 在 PhpStorm 中给出未使用的局部变量错误

PHP: list() giving unused local variable error in PhpStorm

我正在使用在 找到的答案,以便按最喜欢的语言对 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 数组进行排序。

在那个答案中(顺便说一下,它工作得很好),一行是:

list($a, $b) = explode('-', $match[1]) + array('', '');

在 PhpStorm 中,我收到该行的以下错误:

"Unused local variable $b: The value of the variable is overwritten immediately".

我对这条线到底在做什么有点困惑,所以我不知道我是否应该保持不变,或者我是否应该将其修改为:

list($a) = explode('-', $match[1]) + array('', '');

...这似乎也工作正常。

是否应该更改?

您不能使用算术运算符 + 连接数组。基本上你告诉 PHP 将数组转换为标量类型,然后对它们求和,这会产生一个数字(如果数组有元素,则可能为 1,如果没有,则为 0)。

结果是您实际上在做类似的事情:

list($a, $b) = 2;

PHP得出的结论是您没有指定足够的元素来定义列表中的所有变量。

要将两个数组连接在一起,请使用 array_merge()

list($a, $b) = array_merge(explode('-', $match[1]), array('', ''));

措辞令人困惑,因为它是对涵盖两种情况的检查的完整解释,而初始工具提示仅显示第一行,恰好描述了 other 情况。如果你点击 Ctl+F1 你可以阅读完整的文本,哪种更有意义(强调我的):

Unused local variable 'b'. The value of the variable is overwritten immediately. less... (Ctrl+F1)

Inspection info: A variable is considered unused in the following cases:

  • The value of the variable is not used anywhere or is overwritten immediately.
  • The reference stored in the variable is not used anywhere or is overwritten immediately.

这正是这里发生的事情:

list($a, $b) = …

$a 稍后使用但 $b 不是。由于 $b 从未被使用过,这也适用:

list($a) = explode('-', $match[1]) + array('', '');

(请记住,这些检查是防止潜在错误的提示,不一定是错误。)