Search code examples
phpoopreflection

Get all public methods declared in the class, not inherited


What I want to get is the array of all public methods, and ONLY public ones, from the lowest classes in the inheritance tree. For example:

class MyClass {  }

class MyExtendedClass extends MyClass {  }

class SomeOtherClass extends MyClass {  }

And from the inside of MyClass I want to get all PUBLIC methods from MyExtendedClass and SomeOtherClass.

I figured out I can use Reflection Class to do this, however when I do that, I also get methods from the MyClass, and I don't want to get them:

$class = new ReflectionClass('MyClass');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);

Is there a way to do this? Or the only solution I have in this situation is just to filter out the outcomes of the Reflection Class?


Solution

  • No, I don't think you can filter out the parent methods at once. But it'd be quite simple to just filter the results by the class index.

    $methods = [];
    foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method)
        if ($method['class'] == $reflection->getName())
             $methods[] = $method['name'];