Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 仅检索子类的属性_Php_Class_Inheritance_Properties - Fatal编程技术网

Php 仅检索子类的属性

Php 仅检索子类的属性,php,class,inheritance,properties,Php,Class,Inheritance,Properties,我有一门课 class parent{ public $foo; } class child extends parent{ public $lol; public function getFields() { return array_keys(get_class_vars(__CLASS__)); } } 我得到一个包含子属性的数组来 array('foo','lol'); 是否有一个简单的解决方案可以只从子类获取属性?尝试这种方

我有一门课

class parent{
   public $foo;
}

class child extends parent{
   public $lol;

    public function getFields()
    {
        return array_keys(get_class_vars(__CLASS__));
    }
}
我得到一个包含子属性的数组来

array('foo','lol'); 
是否有一个简单的解决方案可以只从子类获取属性?

尝试这种方法(可能包含伪PHP代码:)

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

如链接中所述


这是一个很好的解决方案!你的!!!谁曾链接到这一个

我开始做同样的事情,+1。可能需要添加递归。您也可以跳过父函数,直接在
get_parent_class()
上使用
get_class_vars()
OP:use
array_diff
来获取子字段,或者,get_class_vars(父)可能只起作用:),我懒得尝试:)@KemalDağ
get_class_vars(父)
不起作用,因为当您将其传递给函数时,PHP将其视为字符串文本
'parent'
。@AshwinMukhija非常感谢您,这是一个懒惰的程序员学到的教训:)
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
    }
}
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";
  }
}