0

我制作了一个对象,它应该代表一个数组,但有一些方法。所以我让它实现了本机接口:IteratorAggregateCountable. 这样你就可以foreachcount。到目前为止,一切都很好。

但现在我希望它也像数组一样评估。因此,如果count($object)为零,if($object)则应该评估为false。有Comparable接口之类的吗?

4

2 回答 2

1

使用类型 Juggling

您可以分配预期的 var 类型。

$object = count ( $object );
$object = (array) $object;

同样,如果您想为变量分配其他类型,这里是可能值的列表:

  • (int)
  • (bool)
  • (float)
  • (string)
  • (array)
  • (object)
  • (unset)
  • (binary)

还要检查 this 这个Comparable interface

于 2013-03-25T20:17:24.207 回答
0

The documentation shows everything that evaluates to false:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

As of this list an object will never be considered as false. So the only way is to cast the value of count() to boolean using (bool) if you need to do a strict comparison as pointed out in Tomi Sebastián Juárez's answer.

于 2013-03-25T20:24:36.110 回答