仅检索子类的属性

5

我有一个类似这样的类

class parent{
   public $foo;
}

class child extends parent{
   public $lol;

    public function getFields()
    {
        return array_keys(get_class_vars(__CLASS__));
    }
}

我得到一个包含子属性的数组...

array('foo','lol'); 

有没有一种简单的解决方案只获取子类中的属性?
2个回答

6

如链接所示(如何迭代当前类的属性(不是从父类或抽象类继承))

,这篇文章讨论了如何遍历一个类中的属性。
public function iterate()
{
  $refclass = new ReflectionClass($this);
  foreach ($refclass->getProperties() as $property)
  {
    $name = $property->name;
    if ($property->class == $refclass->name)
      echo "{$property->name} => {$this->$name}\n";
  }
}

这是一种非常好的解决方案,被投票和收藏!感谢你!不管是谁提供了链接!


3
尝试这种方法(可能包含伪 PHP 代码 :))
class parent{
   public $foo;

   public function getParentFields(){
        return array_keys(get_class_vars(__CLASS__));
   }
}

class child extends parent{
   public $lol;

    public function getFields()
    {   
        $parentFields = parent::getParentFields();
        $myfields = array_keys(get_class_vars(__CLASS__));

        // just subtract parentFields from MyFields and you get the properties only exists on child

        return the diff
    }
}

使用parent::getParentFields()函数确定哪些字段是父字段的想法。


2
我开始着手处理同样的事情,+1。可能需要添加递归。您还可以跳过父函数,直接在get_parent_class()上直接使用get_class_vars()。操作:使用array_diff获取子字段。 - Jessica
或者,get_class_vars(parent) 可能会奏效 :), 我太懒了,不想试 :) - Kemal Dağ
@KemalDağ get_class_vars(parent) 不起作用,因为当你将它传递给一个函数时,PHP会将其视为字符串字面量 'parent' - Achrome
@AshwinMukhija 非常感谢,这个教训对于一个懒惰的程序员来说是很好的学习。 - Kemal Dağ

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