How to know the location of a function defined in PHP

Sometimes you want to know the location of a function defined in your php application. For example you are debugging a large online web application or website. To continue debug you want to enter into a function to debug. You don’t have an easy way to download all the files to your location system to do a text search. Also you don’t have access to file system search capabilities on the server. How to get into the function?

How to know the location of a function defined in PHP

To know the location of a function defined in PHP there is an inbuilt tool in form of a class in php. This class is available since php 5.

Here is how to use it. Write this code anywhere in your application but after all the files have been included in your application. For example, it will be good to add this code somewhere the end of your file or near the footer if you are not sure.

[code lang=”php”]$reflFunc = new ReflectionFunction(‘function_name’);
print $reflFunc->getFileName() . ‘:’ . $reflFunc->getStartLine();[/code]

It will display the path to your file where this function was defined. It also shows the line number. This will help you clearly know the location of a function.

However, if  function is not found in your file system or in other words it was not defined anywhere in your php files it will give a fatal error. At worse it would just die your browser page without showing any useful information. Such as, if your server is not configured to display php errors.

To avoid this you must catch the exception and display the useful message. Doing it like the following would do the trick.

[code lang=”php”]try {
$reflFunc = new ReflectionFunction(‘function_name’);
print $reflFunc->getFileName() . ‘:’ . $reflFunc->getStartLine();
} catch (Exception $e) {
print $e->getMessage();
}[/code]

Ref “How to find out where a function is defined?” on github here

Leave a Reply