Get only declared class methods in PHP

Hello, I only need to get the methods declared in the class, not the inherited methods. I need this for cakePHP. I get all the controllers by loading them and getting methods from these controllers. But not only declared methods come, but also inherited ones.

Is there a way to get only declared methods.

+6
oop php cakephp
source share
3 answers

You can do this (though a little more than just) with ReflectionClass

 function getDeclaredMethods($className) { $reflector = new ReflectionClass($className); $methodNames = array(); $lowerClassName = strtolower($className); foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { if (strtolower($method->class) == $lowerClassName) { $methodNames[] = $method->name; } } return $methodNames; } 
+9
source share

From an architectural point of view, I think that reflection should be avoided whenever possible, but take a look at ReflectionClass-> getMethods () if you think you know what you are doing.

 <?php class A { public function x() { } public function y() { } } class B extends A { public function a() { } public function b() { } public function x() { } // <-- defined here } $r = new ReflectionClass('B'); print_r($r->getMethods()); ?> 

You will get a list of methods defined by B and A , along with the class that defined it last. This is the result:

 Array ( [0] => ReflectionMethod Object ( [name] => a [class] => B ) [1] => ReflectionMethod Object ( [name] => b [class] => B ) [2] => ReflectionMethod Object ( [name] => x [class] => B ) [3] => ReflectionMethod Object ( [name] => y [class] => A ) ) 
+1
source share

In response to the comment: "ReflectionClass :: getMethods () sorts the methods by class (first in the inheritance tree), and then by the order that they are defined in the class definition" here - http://php.net/manual/en/reflectionclass .getmethods.php # 115197

I checked it and it seems true. Based on this, we can add a little optimization to the ircmaxell solution to avoid repeating other inherited methods. Some cleanup has also been added to avoid the \ destructor constructor:

 public function getMethods($className) { $methodNames = []; $reflectionClass = new ReflectionClass(className); $publicMethods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC); $lowerClassName = strtolower($className); foreach ($publicMethods as $method) { if (strtolower($method->class) == $lowerClassName) { // You can skip this check if you need constructor\destructor if (!($method->isConstructor() || $method->isDestructor())) { $methodNames[] = $method->getName(); } } else { // exit loop if class mismatch break; } } return $methodNames; } 
0
source share

All Articles