Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check If an object is empty?

Tags:

object

php

How can I check if a PHP object is empty (i.e. has no properties)? The built-in empty() does not work on objects according the doc:

5.0.0 Objects with no properties are no longer considered empty.
like image 663
Justin Avatar asked Sep 26 '11 23:09

Justin


1 Answers

ReflectionClass::getProperties

http://www.php.net/manual/en/reflectionclass.getproperties.php

class A {
    public    $p1 = 1;
    protected $p2 = 2;
    private   $p3 = 3;
}

$a = new A();
$a->newProp = '1';
$ref = new ReflectionClass($a);
$props = $ref->getProperties();

// now you can use $props with empty
echo empty($props);

print_r($props);

/* output:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => p1
            [class] => A
        )

    [1] => ReflectionProperty Object
        (
            [name] => p2
            [class] => A
        )

    [2] => ReflectionProperty Object
        (
            [name] => p3
            [class] => A
        )

)

*/

Note that newProp is not returned in list.

get_object_vars

http://php.net/manual/en/function.get-object-vars.php

Using get_object_vars will return newProp, but the protected and private members will not be returned.


So, depending on your needs, a combination of reflection and get_object_vars may be warranted.

like image 145
webbiedave Avatar answered Sep 30 '22 22:09

webbiedave