php文件的功能列表

zum*_*sha 9 php function list

如何获取在php文件中声明的函数列表

And*_*ore 18

您可以使用以下命令获取当前定义的函数列表get_defined_functions():

$arr = get_defined_functions();
var_dump($arr['user']);
Run Code Online (Sandbox Code Playgroud)

内部函数在索引处,internal而用户定义的函数在索引处user.

请注意,这将输出该调用之前声明的所有函数.这意味着如果您include()使用函数文件,那么它们也将在列表中.除了确保include()在调用之前没有任何文件之外,没有办法分隔每个文件的功能get_defined_functions().


如果必须具有每个文件的函数列表,则以下内容将尝试通过解析源来检索函数列表.

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;
}
Run Code Online (Sandbox Code Playgroud)

使用风险由您自己承担.


joa*_*him 12

您可以在包含文件之前和之后使用get_defined_functions(),并查看第二次添加到数组的内容.由于它们看起来是按照定义的顺序,你可以像这样使用索引:

  $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);
Run Code Online (Sandbox Code Playgroud)


mau*_*ris 9

您可以使用该get_defined_functions()函数在当前脚本中获取所有已定义的函数.

请参阅:http://www.php.net/manual/en/function.get-defined-functions.php

如果要获取在另一个文件中定义的函数,可以尝试使用http://www.php.net/token_get_all,如下所示:

$arr = token_get_all(file_get_contents('anotherfile.php'));
Run Code Online (Sandbox Code Playgroud)

然后,您可以循环查找具有已定义符号的函数标记.可以在http://www.php.net/manual/en/tokens.php找到令牌列表