laravel PHP 7.2 count() 函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50667333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP 7.2 count() function is not working
提问by Nilay Singh
I have a working php application and it is running fine on php 7.0 version. But when I upgrade a php version to 7.2. I am getting this error:
我有一个可用的 php 应用程序,它在 php 7.0 版本上运行良好。但是当我将 php 版本升级到 7.2 时。我收到此错误:
count(): Parameter must be an array or an object that implements Countable
I am getting errors on code where I am comparing my data with count function. For example this is my code:
我在将数据与计数函数进行比较的代码中遇到错误。例如这是我的代码:
$keytest = KeyUser::where('key', '=', $key)->first();
if (count($keytest) == 1) {
//logic ...
}
I am using laravel where I am running a query and counting it if it is equal to 1 then logic should work.
我正在使用 laravel 运行查询并计算它,如果它等于 1,那么逻辑应该可以工作。
So my problem is I have written this kind of logic on many controllers and if I have to change everything one by one it could become nightmare. So is there any way where I can write a global function to make count work as it was working in php older version. What can be the easiest fix.
所以我的问题是我已经在许多控制器上编写了这种逻辑,如果我必须一个一个地更改所有内容,它可能会成为噩梦。那么有什么方法可以编写一个全局函数来使计数在 php 旧版本中工作。什么是最简单的修复。
回答by Nilay Singh
This problem can be handle using disable error handling. Please refer this link for solution: Laravel not compatiable with php 7.2
可以使用禁用错误处理来处理此问题。请参阅此链接以获取解决方案:Laravel not compatiable with php 7.2
Here I found a solution to your problem simply write this code inside your controller or if you want to make it work for whole application write this code in route.php:
在这里,我找到了解决您的问题的方法,只需在您的控制器中编写此代码,或者如果您想让它适用于整个应用程序,请在 route.php 中编写此代码:
//app/Http/routes.php
if (version_compare(PHP_VERSION, '7.2.0', '>=')) {
// Ignores notices and reports all other kinds... and warnings
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
// error_reporting(E_ALL ^ E_WARNING); // Maybe this is enough
}
I know this is not the best solution but it can be a good hack.
我知道这不是最好的解决方案,但它可以是一个很好的黑客。
回答by Khotibul Umam
It's solved when you change your code:
当您更改代码时,它已解决:
$keytest = KeyUser::where('key', '=', $key)->first();
if ($keytest) {
//logic ...
}