如何检查对象是否为空? [英] How to check If an object is empty?

查看:131
本文介绍了如何检查对象是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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.

Note that newProp is not returned in list.

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

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

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

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

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

这篇关于如何检查对象是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆