【问题标题】:How to check If an object is empty?如何检查对象是否为空?
【发布时间】:2011-09-26 23:54:11
【问题描述】:

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

5.0.0 Objects with no properties are no longer considered empty.

【问题讨论】:

    标签: php object


    【解决方案1】:

    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。

    【讨论】:

      【解决方案2】:

      这里是解决方案:;

      $reflect = new ReflectionClass($theclass);
      $properties = $reflect->getProperties();
      
      if(empty($properties)) {
          //Empty Object
      }
      

      【讨论】:

        【解决方案3】:

        你能用一些代码详细说明一下吗?我不明白你想要完成什么。

        你可以像这样在对象上调用一个函数:

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

        【讨论】:

          【解决方案4】:

          我相信(不完全确定)您可以覆盖对象的 isset 函数。 在类中,您可以提供__isset() 的实现,并让它相应地返回设置的属性。

          尝试阅读以下内容: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

          【讨论】:

            猜你喜欢
            • 2013-10-11
            • 2019-06-09
            • 2013-02-13
            • 1970-01-01
            • 1970-01-01
            • 2017-05-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多