phpreflectionphp-5.3

PHP Reflection: How to know if a ReflectionMethod is inherited?


In the ReflectionMethod documentation, I can't find anything to know wether a method was inherited from its parent class or defined in the reflected class.

Edit: I use ReflectionClass::getMethods(). I want to know for each method if it has been defined in the class being reflected, or if it has been defined in a parent class. In the end, I want to keep only the methods defined in the current class.

class Foo {
    function a() {}
    function b() {}
}

class Bar extends Foo {
    function a() {}
    function c() {}
}

I want to keep a and c.


Solution

  • You should be able to call ReflectionMethod::getDeclaringClass() to get the class declaring the method. Then a call to ReflectionClass::getParentClass() to get the parent class. Lastly a call to ReflectionClass::hasMethod() will tell you if the method was declared in the parent class.

    Example:

    <?php
    class Foo {
        function abc() {}
    }
    
    class Bar extends Foo {
        function abc() {}
        function def() {}
    }
    
    
    $bar = new Bar();
    
    $meth = new ReflectionMethod($bar, "abc");
    $cls = $meth->getDeclaringClass();
    $prnt = $cls->getParentClass();
    
    if ($cls->hasMethod($meth->name)) {
        echo "Method {$meth->name} in Bar\n";
    }
    if ($prnt->hasMethod($meth->name)) {
        echo "Method {$meth->name} in Foo\n";
    }
    
    $meth = new ReflectionMethod($bar, "def");
    $cls = $meth->getDeclaringClass();
    $prnt = $cls->getParentClass();
    
    if ($cls->hasMethod($meth->name)) {
        echo "Method {$meth->name} in Bar\n";
    }
    if ($prnt->hasMethod($meth->name)) {
        echo "Method {$meth->name} in Foo\n";
    }