How do I know if a stdClass is empty?

3

In PHP, to check if a array is empty we can use the language function (or language constructor) empty .

So:

$a = array();

$b = array(1, 2);

var_dump(empty($a), empty($b)); // Imprime: bool(true), bool(false)

But the same does not happen with stdClass .

$a = (object) array();

$b = (object)array('nome' => 'wallace');

$c = new stdClass(); // A mesma coisa que $a

var_dump(empty($a), empty($b), empty($c)); // Imprime: bool(false), bool(false), bool(false)

See in IDEONE

So what is the way to know that a stdClass object is empty or not in PHP?

    
asked by anonymous 18.10.2015 / 00:35

2 answers

4

You could use the get_object_vars function to return the properties of stdClass to array . Then you could use the function count or empty , to know if it is empty or not.

Example:

$object = new stdClass;

count(get_object_vars($object)) == 0;// Imprime: bool(true)

$array = get_object_vars($object);

var_dump(empty($array)); // Imprime: bool(true);
    
18.10.2015 / 00:42
0

Just for extra help, if anyone needs it, we could do this by using a loop over stdClass . If you enter foreach it is because it is an object with properties. If not, it is empty.

See:

function is_empty_object(stdClass $object)
{

    foreach($object as $value) return false;

    return true;
}
    
18.10.2015 / 01:07