How to find out where a function is defined using PHP ?
When we do projects then it includes multiple modules where each module divided into multiple files and each file containing many lines of code. So when we declare a function somewhere in the files and forget that what the function was doing or want to change the code of that function but can’t find that where the function is! So this article will help you to find the location of the function.
In order to get the location of the function in PHP we can use the inbuilt class ReflectionFunction(). When the name of the function regarding which we are requiring details is passed to the class constructor, it gets several details regarding that function.
- getFileName: It returns the file location of the function.
- getNumberOfParameters: It returns the number of parameters passed to the function.
- getStartLine: It return the starting line of the function.
$details = new ReflectionFunction('function_name');
Then use the above functions to access whatever you need. Paste the below code into main code and you will get the details of that function.
Steps to run the code:
- Create a file named as file_name.php
- Copy the above given code into the file.
- Save the file into your localhost server folder. In the case of WampServer the look for the folder ‘www’ inside ‘wamp64’ folder in C drive and save the file there.
- Run your wamp server.
- Open any browser and type localhost/fun.php to get the following output.
C:\wamp64\www\file_name.php : 2
Below examples illustrates the ReflectionFunction in PHP:
Example 1: Suppose in the given code we want to find the location of the function ‘printing’. In the output, the filename and location of the function printing can be seen.
File location : /home/7de5f19b219d214c719df5f3839a7f61.php, Starting line : 2, Parameters passed : 0
Example 2: Suppose in the given code we want to find the location of the function ‘geeks’. In the output, the filename, location, start line and the parameter passed of the function geeks can be seen.
File location :/home/dd96d70bdf5ff03fea0ea24110bae9ff.php Starting line :7 No. of parameters passed :0
Please Login to comment...