开发者

How to find if a perversely constructed object is empty in PHP

I'm working with an object fed back from a class. For some reason, the class spits out an object with numbered properties (0, 1, 2, etc.). I need to check if the object is empty. The standard trick, empty(get_object_vars($obj)), won't work, because get_object_vars returns an empty array even when the object has (numbered) properties.

For reference, the object I'm 开发者_如何学Cworking with is the one returned by the legislatorsZipCode method of the PHP interface for Sunlight's API. You can see a print_r of a sample response here.


Judging by the code, the author made the mistake of casting a numerically indexed array to an object. This makes getting object properties by name impossible, though you should still be able to foreach over it. You can also simply cast it back to an array: $results = (array) $obj;. Then, count the array.


This appears to work:

if (current($obj) === false)
  echo "is empty\n";

It probably is doing an implicit cast to an array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜