abstract class foo
{
public $blah;
}
class bar extends foo
{
public $baz;
}
鉴于我有一个继承自抽象foo
类的bar
类,我将如何获得仅存在于bar
但不存在于{{1}的实例变量数组(即foo
级别定义的属性)?在上面的示例中,我希望bar
但不是baz
。
答案 0 :(得分:3)
正如hakre所说,使用Reflection
。抓住类的父类,并在属性上执行diff,如下所示:
function get_parent_properties_diff( $obj) {
$ref = new ReflectionClass( $obj);
$parent = $ref->getParentClass();
return array_diff( $ref->getProperties(), $parent->getProperties());
}
你会这样称呼它:
$diff = get_parent_properties_diff( new bar());
foreach( $diff as $d) {
echo $d->{'name'} . ' is in class ' . $d->{'class'} . ' and not the parent class.' . "\n";
}
在this demo中查看它,输出:
baz is in class bar and not the parent class.