我们正在升级 Laravel 项目,其中包括从 php7 到 php8 的语言升级。考虑这段代码:
$a = new stdClass()
count($a)
将导致:
// php7
==> 1
// php8
==> TypeError count(): Argument #1 ($value) must be of type Countable|array
现在我们的应用程序相当大,有很多很多的小片段,并且在许多地方使用了 count 来处理可能不应该使用的事情。我涵盖了大部分内容,但理想情况下我希望有某种后备。有没有办法全局覆盖 Laravel 应用程序中内置的 count 函数,希望能做到这样的事情:
// very general pseudocode
function newCount($foo) {
try {
return count($foo);
} except {
\Log::warning('used count on non Countable|array')
return 1;
}
}
然后以某种方式绑定它:
// anywhere in the app code
count($a) // ==> will call newCount($a) instead