正如我们所讨论的,有多种方法可以实现count()
而不是发出E_WARNING
.
在 PHP 7.3 中添加了一个新功能is_countable
,专门用于解决应用程序在其代码E_WARNING
中采用的问题和普遍性。is_array($var) || $var instanceof \Countable
在 PHP 7.2 中,在尝试计算不可数事物时添加了警告。在那之后,每个人都被迫搜索和更改他们的代码,以避免它。通常,以下代码成为标准:
if (is_array($foo) || $foo instanceof Countable) {
// $foo is countable
}
https://wiki.php.net/rfc/is-countable
自定义函数替换
因此,解决问题的最佳方法似乎是执行与 PHP 相同的功能is_countable
并创建自定义函数以确保符合count
.
示例 https://3v4l.org/8M0Wd
function countValid($array_or_countable, $mode = \COUNT_NORMAL)
{
if (
(\PHP_VERSION_ID >= 70300 && \is_countable($array_or_countable)) ||
\is_array($array_or_countable) ||
$array_or_countable instanceof \Countable
) {
return \count($array_or_countable, $mode);
}
return null === $array_or_countable ? 0 : 1;
}
结果
array: 3
string: 1
number: 1
iterator: 3
countable: 3
zero: 1
string_zero: 1
object: 1
stdClass: 1
null: 0
empty: 1
boolt: 1
boolf: 1
Notice: Undefined variable: undefined in /in/8M0Wd on line 53
undefined: 0
垫片is_countable()
功能
使用上述替换函数,也可以在 中填充is_countable
,PHP <= 7.2
因此仅在需要时使用,开销最小。
示例 https://3v4l.org/i5KWH
if (!\function_exists('is_countable')) {
function is_countable($value)
{
return \is_array($value) || $value instanceof \Countable;
}
}
function countValid($array_or_countable, $mode = \COUNT_NORMAL)
{
if (\is_countable($array_or_countable)) {
return \count($array_or_countable, $mode);
}
return null === $array_or_countable ? 0 : 1;
}
忽略count()
警告
由于 的功能count()
没有改变,并且过去通常不会发出警告。使用自定义函数的替代方法是使用错误控制运算符完全忽略警告@
警告:这种方法会影响将未定义的变量视为消息NULL
而不显示Notice: Undefined variable:
消息。
示例 https://3v4l.org/nmWmE
@count($var);
结果
array: 3
string: 1
number: 1
iterator: 3
countable: 3
zero: 1
string_zero: 1
object: 1
stdClass: 1
null: 0
empty: 1
boolt: 1
boolf: 1
---
Undefined: 0
count()
使用 APD 扩展替换
至于替换PHP内部函数count()
。有一个 PECL 扩展APD
(高级 PHP 调试器),它允许override_function
在核心 PHP 函数上工作。count
正如扩展名所暗示的那样,它在技术上是用于调试的,但它是替换自定义函数的所有实例的可行替代方案。
例子
\rename_function('count', 'old_count');
\override_function('count', '$array_or_countable,$mode', 'return countValid($array_or_countable,$mode);');
if (!\function_exists('is_countable')) {
function is_countable($value)
{
return \is_array($value) || $value instanceof \Countable;
}
}
function countValid($array_or_countable, $mode = \COUNT_NORMAL)
{
if (\is_countable($array_or_countable)) {
return \old_count($array_or_countable, $mode);
}
return null === $array_or_countable ? 0 : 1;
}