PHP从子类中获取重写的方法

时间:2010-04-19 16:19:44

标签: php reflection

鉴于以下情况:

<?php

class ParentClass {

    public $attrA;
    public $attrB;
    public $attrC;

    public function methodA() {}
    public function methodB() {}
    public function methodC() {}

}

class ChildClass extends ParentClass {

    public $attrB;

    public function methodA() {}
}

如何获取在ChildClass中重写的方法列表(最好是类变量)?

谢谢, 乔

编辑:修正了糟糕的延伸。任何方法,而不仅仅是公共方法。

2 个答案:

答案 0 :(得分:14)

反思是正确的,但你必须这样做:

$child  = new ReflectionClass('ChildClass');

// find all public and protected methods in ParentClass
$parentMethods = $child->getParentClass()->getMethods(
    ReflectionMethod::IS_PUBLIC ^ ReflectionMethod::IS_PROTECTED
);

// find all parent methods that were redeclared in ChildClass
foreach($parentMethods as $parentMethod) {
    $declaringClass = $child->getMethod($parentMethod->getName())
                            ->getDeclaringClass()
                            ->getName();

    if($declaringClass === $child->getName()) {
        echo $parentMethod->getName(); // print the method name
    }
}

属性相同,只需使用getProperties()代替。

答案 1 :(得分:4)

您可以使用ReflectionClass来实现此目的:

$ref = new ReflectionClass('ChildClass');

print_r($ref->getMethods());
print_r($ref->getProperties());

这将输出:

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => methodA
            [class] => ChildClass
        )

)

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => attrB
            [class] => ChildClass
        )

)

有关反思的更多有用信息,请参阅手册:http://uk3.php.net/manual/en/class.reflectionclass.php