PHP – Get method definition from object instance

When debugging complex applications you sometimes need to find out where a method of an object instance has been defined. With several levels of inheritance this can sometimes become quite time consuming. This is where PHP’s Reflektion API comes in handy. This API allows you to reverse-engineer classes, functions & methods.

$foo->bar();

If see in your code that an object instance $foo calls a method bar and you want to know in which file bar is defined.

You could use get_class($foo) to find the name of the class, then find the class definition in your code and then go backwards through the classes the class inherited from, to find the method definition. Using the Reflektion API allows you to find the file in one step.

$rc = new ReflectionClass($foo);
$method = $rc->getMethod('bar');
echo $method->getFileName();

Have a look at ReflectionMethod for more details.

I'm available for contracting work. Check out my LinkedIn profile and my portfolio page for an overview of my skills and experience. If you are interested in working with me please use the contact form to get in touch.

PHP – Get method definition from object instance

Leave a Reply

Your email address will not be published. Required fields are marked *