7

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.

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Here is the solution:;

$reflect = new ReflectionClass($theclass);
$properties = $reflect->getProperties();

if(empty($properties)) {
    //Empty Object
}

Comments

2

Can you elaborate this with some code? I don't get what you're trying to accomplish.

You could anyhow call a function on the object like this:

public function IsEmpty()
{
    return ($this->prop1 == null && $this->prop2 == null && $this->prop3 == null);
}

Comments

1

I believe (not entirely sure) that you can override the isset function for objects. In the class, you can provide an implemention of __isset() and have it return accordingly to which properties are set.

Try reading this: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.