Tutorial :Quick way to see what functions/libraries are used by a PHP project or code



Question:

Is there a way to generate a list of all the functions being used by a piece of code?

With Java it is easy as you can just copy the import statements at the top of the code. With PHP, as you don't need to import the library, it is more difficult.

I'm after a quick solution, if there is one, for documentation purposes.


Solution:1

You can see what is used with these functions:

// get vars  $vars = get_defined_vars();  // get constants  $consts = get_defined_constants();  // get functions  $funcs = get_defined_functions();    var_dump($vars);  var_dump($consts);  var_dump($funcs);  

More Info:


Solution:2

You can use get_declared_classes, get_declared_interfaces, and get_defined_functions but that won't show whether they have been called or not just whether they have been defined (included).


Solution:3

get_defined_functions() gives an array listing all functions (user-defined and built-in) that are available to your code, but doesn't tell you whether they are actually used or not.

EDIT

There are also "Code Coverage" tools including features in PHPUnit and XDebug that can provide this information based on actual execution of the code


Solution:4

I'd say this is much harder in PHP, considering features such as call_function and eval that allow for wild ways of calling functions. Your best bet is probably to find all instances of include, include_once, require and require_once, but you can't be sure that your list is concise this way. There's also class autoloading to be considered.


Solution:5

I have been thinking about this recently. My thoughts are that you can add some logic to your autoloader to save everything that gets called to a log file (watching for duplicate entries)

Ideally, this could be something that you could turn on, go through your whole project, and then check the log file to see what's used and then turn it off. (For me this would mean it's only active if my application is in debug mode)

My solution is not so much to see what's defined at any certain point in execution, but more to keep track of your custom functions/libraries that needs to be included when uploading your project to a server. For example if you have a bunch of common libraries and you need to just to remember which ones to upload for a certain project. This might not be specifically what you're asking, but I thought it was close enough to your question to mention it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »