php 如何在php中检查stdClass对象是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14137104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if stdClass object is empty or not in php?
提问by Vipul Sharma
Possible Duplicate:
How to Check if an Object is empty in PHP
可能的重复:
如何在 PHP 中检查对象是否为空
I have this empty object
我有这个空对象
Array (
[cart_items] => stdClass Object
(
)
)
When I use empty()/is_null(), it doesn't work. When I use sizeof($object), it returns one.
当我使用时empty()/is_null(),它不起作用。当我使用时sizeof($object),它返回一个。
How can I check it?
我该如何检查?
回答by KingCrunch
Cast to an array first
首先投射到数组
$tmp = (array) $object;
var_dump(empty($tmp));
The reason is, that an object is an object and there is no useful definition of "an empty object", because there are enough classes out there, that only contains methods, but no properties. Should they considered as "empty"?
原因是,一个对象是一个对象,没有“空对象”的有用定义,因为那里有足够的类,只包含方法,但没有属性。他们应该被视为“空”吗?
回答by moonwave99
Check if count( (array)$yourObject) ) == 0.
检查是否count( (array)$yourObject) ) == 0。
But I'd better define my own class, and provide it with a meaningful isEmpty()method.
但我最好定义我自己的类,并为其提供一个有意义的isEmpty()方法。

