php文件的函数列表 [英] Function list of php file
问题描述
如何获取在php文件中声明的函数列表
您可以获取当前定义的函数列表通过使用 get_defined_functions()
: p>
$ arr = get_defined_functions();
var_dump($ arr ['user']);
内部函数位于索引内部
,而用户 - 定义的函数位于索引 user
。
请注意,这将输出在该调用之前声明的所有函数。这意味着如果您使用函数 include()
文件,那些也将在列表中。除了确保您不需要 include()
调用 get_defined_functions()之前的任何文件
。
如果您必须拥有每个文件的函数列表,以下将尝试通过解析源来检索函数列表。
函数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;
休息;
case T_FUNCTION:
if(!$ inClass)$ nextStringIsFunc = true;
休息;
case T_STRING:
if($ nextStringIsFunc){
$ nextStringIsFunc = false;
$ functions [] = $ token [1];
}
break;
//匿名函数
case'(':
case';':
$ nextStringIsFunc = false;
break;
//排除类
case'{':
if($ inClass)$ bracesCount ++;
break;
$ b $ case'}':
if($ inClass){
$ bracesCount--;
if($ bracesCount === 0)$ inClass = false;
}
break;
}
}
return $ functions;
}
请自担风险。
How to get list of functions that are declared in a php file
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.
这篇关于php文件的函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!