如何检查一个对象是否为空?

7

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

5.0.0 Objects with no properties are no longer considered empty.
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
        )

)

*/

请注意,列表中不返回newProp

get_object_vars

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

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


因此,根据您的需求,可能需要结合反射和get_object_vars

5
这是解决方案:
$reflect = new ReflectionClass($theclass);
$properties = $reflect->getProperties();

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

2

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

无论如何,你都可以像这样在对象上调用一个函数:

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

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接