San*_*oku 5 php inheritance properties class
我有一个类似的课程
class parent{
public $foo;
}
class child extends parent{
public $lol;
public function getFields()
{
return array_keys(get_class_vars(__CLASS__));
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个包含子属性的数组到...
array('foo','lol');
Run Code Online (Sandbox Code Playgroud)
是否只有一个简单的解决方案来获取子类的属性?
如链接中发布的如何遍历当前类属性(不是从父类或抽象类继承)?
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";
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个很好的解决方案,被投票和收藏!你的!!!谁曾经联系过这个!
尝试这种方法(可能包含伪 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
}
}
Run Code Online (Sandbox Code Playgroud)
使用parent::getParentFields()函数来确定哪些字段是父字段的想法。