Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get overridden methods from child class

Tags:

php

reflection

Given the following case:

<?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() {}
}

How can I get a list of methods (and preferably class vars) that are overridden in ChildClass?

Thanks, Joe

EDIT: Fixed bad extends. Any methods, not just public ones.

like image 958
Joe Mastey Avatar asked Apr 19 '10 16:04

Joe Mastey


2 Answers

Reflection is correct, but you would have to do it like this:

$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
    }
}

Same for Properties, just you would use getProperties() instead.

like image 74
Gordon Avatar answered Sep 22 '22 03:09

Gordon


You can use ReflectionClass to achieve this:

$ref = new ReflectionClass('ChildClass');

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

This will output:

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

)

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

)

See the manual for more useful information on reflection: http://uk3.php.net/manual/en/class.reflectionclass.php

like image 36
Janci Avatar answered Sep 23 '22 03:09

Janci