可数对象和空

时间:2012-05-25 10:10:01

标签: php count

如果对没有元素的数组执行empty(),则会得到真实。但是,如果对Countable对象执行empty()且计数为0,则会得到false。在我看来,0计数Countable应该被认为是空的。我错过了什么吗?

<?php

class Test implements Countable
{
    public $count = 0;

    public function count ()
    {
        return intval (abs ($this -> count));
    }
}

$test = new Test ();

var_dump (empty ($test));
var_dump (count ($test));

$test -> count = 10;

var_dump (empty ($test));
var_dump (count ($test));

我本来期望第一次调用empty来返回true,但事实并非如此。

是否有合理的理由,或者是一个错误?

2 个答案:

答案 0 :(得分:8)

来自docs

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

* "" (an empty string)
* 0 (0 as an integer)
* 0.0 (0 as a float)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

我认为您案例中的$test仍然被视为Object,这不在空的列表中,而是TRUE

答案 1 :(得分:5)

如上所述,empty()不认为count($obj) == 0为&#34;为空&#34;。这并不像预期的那样工作的原因是因为数组没有实现Countable,即

array() instanceof Countable // false

可能是一个明显的解决方法,但我想在此发布此内容。

function is_empty ($val) {
  return empty($val) || ($val instanceof Countable && empty(count($val)));
}

示例:

class Object implements Countable {

  protected $attributes = array();

  // ...

  public function count () {
    return count($this->attributes);
  }

}

$obj = new Object();
is_empty($obj) // TRUE

我应该注意这个解决方案适用于我的情况,因为我已经将is_empty()与其他is_*方法一起定义为漂亮。