Учитывая следующий случай:
<?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?
Спасибо, Joe
Править: Зафиксированный плохо расширяется. Любые методы, не только общедоступные.
Отражение правильное, но вы должны сделать это следующим образом:
$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 ()
.
Вы можете использовать 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