PHP 7.2 计数错误 [英] PHP 7.2 Count error

查看:27
本文介绍了PHP 7.2 计数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告:count():参数必须是数组或对象实现 Countable in...

Warning: count(): Parameter must be an array or an object that implements Countable in...

我在以下行收到上述错误.

I'm getting the above error on the following line.

if (0 >= count($this->xprop))

有人能帮我理解这个吗?我对 PHP 相当陌生.问题显然在于 $this->xprop 不是数组.在我升级到 PHP 7.2 之前,这不是问题.我怎样才能解决这个问题?带有警告的代码是否仍在执行,还是会导致执行失败?

Can someone help me understand this? I'm fairly new to PHP. The issue is obviously with $this->xprop not being an array. It wasn't an issue before I upgraded to PHP 7.2. How can I get around this? Are code with warnings still being executed or is this going to cause execution to fail?

我已经尝试按照 此处的第二个答案进行操作 没有运气.接受的答案对我来说是不可接受的,因为它更像是一种黑客行为.

I've tried to follow the second answer on here with no luck. The accepted answer is not acceptable to me as it is more of a hack.

推荐答案

PHP 7.2 在尝试对未设置的变量进行计数或获取其大小时抛出错误.在以前的版本中,作者会通过对变量进行计数(或 sizeof'ing)并在未设置的变量上获取0"来快捷地检查变量是否已设置.

PHP 7.2 throws an error when trying to count, or get the size of, a variable that isn't set. In previous versions, authors would shortcut checking to see if the variable was set by just counting (or sizeof'ing) it, and getting "0" on an unset variable.

解决办法是先检查是否设置好再计数:

The solution is to check to see if it's set before counting it:

if (isset($this->xprop) && count($this->xprop) == 0)

您上面的示例实际上是负逻辑,并且是一种非常奇怪的陈述如果此数组的大小为零或小于零"(这是不可能的)的方式.因此,按照上面的示例,符合 PHP 7.2 的版本将使用 empty:

Your example above is actually negative logic, and is a pretty strange way of stating "if the size of this array is zero, or less than zero" (which is impossible). So, following your example above, the PHP 7.2 compliant version would be to use empty:

if (empty($this->xprop))

... 因为一个变量可以被设置 ($xprop = array()) 但仍然是空的.

... because a variable can be set ($xprop = array()) but still be empty.

对不起,如果这有点不清楚;来晚了!

Sorry if this is a bit unclear; it's late here!

犯规

这篇关于PHP 7.2 计数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆