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:usearray_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";
}
}