如何检查对象是否为空?

Jus*_*tin 7 php object

如何检查PHP对象是否为空(即没有属性)?empty()根据文档,内置函数不适用于对象:

5.0.0 Objects with no properties are no longer considered empty.
Run Code Online (Sandbox Code Playgroud)

web*_*ave 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
        )

)

*/
Run Code Online (Sandbox Code Playgroud)

请注意,newProp列表中未返回.

get_object_vars

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

使用get_object_vars将返回newProp,但不会返回受保护和私有成员.


因此,根据您的需要,可以保证反射和get_object_vars的组合.


Jus*_*tin 5

这是解决方案:;

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

if(empty($properties)) {
    //Empty Object
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ter 2

您能用一些代码详细说明吗?我不明白你想要实现什么目标。

无论如何,您可以像这样调用对象上的函数:

public function IsEmpty()
{
    return ($this->prop1 == null && $this->prop2 == null && $this->prop3 == null);
}
Run Code Online (Sandbox Code Playgroud)