How to find if an object is empty or not in PHP.
Following is the code in which $obj
is holding XML data. How can I check if it\'s empty or not?
You can cast to an array and then check if it is empty or not
$arr = (array)$obj;
if (!$arr) {
// do stuff
}
Using empty()
won't work as usual when using it on an object, because the __isset()
overloading method will be called instead, if declared.
Therefore you can use count()
(if the object is Countable).
Or by using get_object_vars()
, e.g.
get_object_vars($obj) ? TRUE : FALSE;
If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null. Use the following code:
$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!";
}
If an object is "empty" or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.
PHP itself regards every instance of a class as not empty.
class Test { }
$t = new Test();
var_dump(empty($t));
// results in bool(false)
There cannot be a generic definition for an "empty" object. You might argue in the above example the result of empty()
should be true
, because the object does not represent any content. But how is PHP to know? Some objects are never meant to represent content (think factories for instance), others always represent a meaningful value (think 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.
Another possible solution which doesn't need casting to array
:
// 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 ) );