php's count() first casts to array, but casting can produce an empty array, depends by how the object is implemented (extensions' objects are often affected by those issues)
class Test { }
$t = new Test();
var_dump(empty($t));
// results in bool(false)
“空”对象不能有泛型定义。在上面的例子中,您可能认为 empty()的结果应该是 true,因为该对象不表示任何内容。但是 PHP 怎么知道呢?有些对象永远不会表示内容(比如说工厂) ,而有些对象总是表示一个有意义的值(比如说 new DateTime())。
In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty() method in the object.
// test setup
class X { private $p = 1; } // private fields only => empty
$obj = new X;
// $obj->x = 1;
// test wrapped into a function
function object_empty( $obj ){
foreach( $obj as $x ) return false;
return true;
}
// inline test
$object_empty = true;
foreach( $obj as $object_empty ){ // value ignored ...
$object_empty = false; // ... because we set it false
break;
}
// test
var_dump( $object_empty, object_empty( $obj ) );
$obj = simplexml_load_file($url);
if (!(bool)$obj) {
print "This variable is null, 0 or empty";
} else {
print "Variable is an object or a primitive type!";
}
$obj = simplexml_load_file($url);
if ( !array_filter((array)$obj) )
{
// all properties falsey or no properties at all
}
如果 SimpleXMLElement 的深度超过一级,可以从将其转换为纯数组开始:
$obj = simplexml_load_file($url);
// `json_decode(json_encode($obj), TRUE)` can be slow because
// you're converting to and from a JSON string.
// I don't know another simple way to do a deep conversion from object to array
$array = json_decode(json_encode($obj), TRUE);
if ( !array_filter($array) )
{
// empty or all properties falsey
}
Old Answer (simple object):
If you want to check if a simple object (type stdClass) is completely empty (no keys/values), you can do the following:
// $obj is type stdClass and we want to check if it's empty
if ( $obj == new stdClass() )
{
echo "Object is empty"; // JSON: {}
}
else
{
echo "Object has properties";
}