How to get list of functions that are declared in a php file
PHP has over 1000 built-in functions that can be called directly from within a script to perform a specific task in PHP Functions.
PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents the file mode for example read-only, read-write, write-only etc.
The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. This function will only work on numerical arrays.
You can get a list of currently defined function by using get_defined_functions()
:
$arr = get_defined_functions();
var_dump($arr['user']);
Internal functions are at index internal
while user-defined function are at index user
.
Note that this will output all functions that were declared previous to that call. Which means that if you include()
files with functions, those will be in the list as well. There is no way of separating functions per-file other than making sure that you do not include()
any file prior to the call to get_defined_functions()
.
If you must have the a list of functions per file, the following will attempt to retrieve a list of functions by parsing the source.
function get_defined_functions_in_file($file) {
$source = file_get_contents($file);
$tokens = token_get_all($source);
$functions = array();
$nextStringIsFunc = false;
$inClass = false;
$bracesCount = 0;
foreach($tokens as $token) {
switch($token[0]) {
case T_CLASS:
$inClass = true;
break;
case T_FUNCTION:
if(!$inClass) $nextStringIsFunc = true;
break;
case T_STRING:
if($nextStringIsFunc) {
$nextStringIsFunc = false;
$functions[] = $token[1];
}
break;
// Anonymous functions
case '(':
case ';':
$nextStringIsFunc = false;
break;
// Exclude Classes
case '{':
if($inClass) $bracesCount++;
break;
case '}':
if($inClass) {
$bracesCount--;
if($bracesCount === 0) $inClass = false;
}
break;
}
}
return $functions;
}
Use at your own risk.
You can use get_defined_functions() before and after you include the file, and look at what gets added to the array the second time. Since they appear to be in order of definition, you can just use the index like this:
$functions = get_defined_functions();
$last_index = array_pop(array_keys($functions['user']));
// Include your file here.
$functions = get_defined_functions();
$new_functions = array_slice($functions['user'], $last_index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With