1

For example I have a class A which extends class B and B extends C and so on.

Now I can get all the function which is accessible in class A by php function getClassMethods($this);

But if I found a function call in Class A like $this->someFunction(); and because of Abstraction, I unable to find in which class the someFuntion() is defined.

Is there any way to find this ?

3

Yes you could do this using reflection. Here I have prepared a function for you to get the name of class from method name.

Approach 1:

function getMethodClassName($childClassName, $methodName)
{
    $class = new ReflectionClass($childClassName);
    $methods = $class->getMethods();
    foreach ($methods as $method)
    {
        if($method->getName() == $methodName){
            return $method->class;
        }

    }
    return null;
}

Approach 2(Credit @DavidManners ):

function getMethodClassName($childClassName, $methodName)
{   
    try{
        $class = new ReflectionClass($childClassName);
        $methodInfo = $class->getMethod($methodName);
        return $methodInfo->class;
    }catch(ReflectionException $e){
        return null;
    } 
}

Simply call this method

echo getMethodClassName(get_class($objC), "someFunction");
echo getMethodClassName("A", "someFunction");

Thanks & keep coding.

| improve this answer | |
  • Oh very nice. I didn't know you could do that with the reflection class. One slight improvement is you could call $class->getMethod($methodName) rather than getMethods() then you do not have to loop over all methods as this could get messy with bigger classes. – David Manners May 15 at 7:30
  • Thanks @DavidManners, updated the answer. – Abdul Pathan May 15 at 10:11
0

If this is just for you to have a look at classes when developing then I would suggest and IDE such as PHPStorm which has the option to show the structure of classes including all parent methods (see https://www.jetbrains.com/help/phpstorm/viewing-structure-of-a-source-file.html#).

But if you want to do this via code I think you would have to do something with get_parent_class and get_class_methods. I think you would need to recursively call get_parent_class(ClassName::class) down the class hierarchy while calling get_class_methods on the resulting class until you find the one without your method. Then the class will be defined in the last class to have this method in it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.