获取实例和实例属性的父实例之间的区别

时间:2012-10-26 16:46:12

标签: php reflection

abstract class foo
{
    public $blah;
}

class bar extends foo
{
    public $baz;
}

鉴于我有一个继承自抽象foo类的bar类,我将如何获得仅存在于bar但不存在于{{1}的实例变量数组(即foo级别定义的属性)?在上面的示例中,我希望bar但不是baz

1 个答案:

答案 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.