0

I made an object that was suposed to represent an array, but with a few methods. So I made it implement the native interfaces: IteratorAggregate and Countable. That way you can foreach and count it. So far so good.

But now I want it to evaluate like an array as well. So, if count($object) is zero, if($object) is suposed to evaluate as false. Is there a Comparable interface or something?

Hugo Mota
  • 11,200
  • 9
  • 42
  • 60

2 Answers2

1

Use type Juggling.

You can assign the expected type of your var.

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

The same way, if you want to assign to your variable some other type, here is list of possible values:

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

Also check this this Comparable interface.

Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51
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.

Community
  • 1
  • 1
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
  • Well, there's that. But i'm trying to keep an open mind here. Few weeks ago I didn't know one could `foreach` or `count` an object either. Who knows... – Hugo Mota Mar 25 '13 at 20:32