给定以下情况:
<?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 中被覆盖的方法列表(最好是类变量)?
谢谢, 乔
编辑:修复了错误的扩展。任何方法,而不仅仅是公共(public)方法。
最佳答案
反射是正确的,但你必须这样做:
$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
}
}
Properties 也一样,只是您会使用 getProperties()
代替。
关于PHP 从子类中获取覆盖的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669046/