加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何检查对象是否为空?

发布时间:2020-12-13 18:27:12 所属栏目:PHP教程 来源:网络整理
导读:如何检查 PHP对象是否为空(即没有属性)?根据doc,内置的empty()不适用于对象: 5.0.0 Objects with no properties are no longer considered empty. ReflectionClass :: GetProperties中 http://www.php.net/manual/en/reflectionclass.getproperties.php cl
如何检查 PHP对象是否为空(即没有属性)?根据doc,内置的empty()不适用于对象:
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不会在列表中返回.

get_object_vars

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读