php文件的函数列表

php文件的函数列表,php,list,function,Php,List,Function,如何获取php文件中声明的函数列表您可以使用get_defined_functions()函数获取当前脚本中所有已定义的函数 见: 如果要获取在另一个文件中定义的函数,可以尝试使用以下方法: $arr = token_get_all(file_get_contents('anotherfile.php')); $functions = get_defined_functions(); $last_index = array_pop(array_keys($functions['user

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

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

见:

如果要获取在另一个文件中定义的函数,可以尝试使用以下方法:

$arr = token_get_all(file_get_contents('anotherfile.php'));
  $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);
<?php
    error_reporting(E_ALL ^ E_NOTICE); // Or we get these undefined index errors otherwise use other method to search array

    // Get the file and get all PHP language tokens out of it
    $arr = token_get_all(file_get_contents('Functions.php'));

    //var_dump($arr); // Take a look if you want

    //The array where we will store our functions
    $functions = array();

    // loop trough
    foreach($arr as $key => $value){

            //filter all user declared functions
        if($value[0] == 334){
                   //Take a look for debug sake
            //echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>';

                    //store third value to get relation
                    $chekid = $value[2];
        }

            //now list functions user declared (note: The last check is to ensure we only get the first peace of information about the function which is the function name, else we also list other function header information like preset values)
        if($value[2] == $chekid && $value[0] == 307 && $value[2] != $old){

                    // just to see what happens
                    echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>';
                    $functions[] = $value[1];
                    $old = $chekid; 
        }
    }
?>

然后,您可以循环查找定义了符号的函数标记。可以找到令牌列表

您可以使用以下方法获得当前定义函数的列表:

内部函数位于索引
Internal
,而用户定义函数位于索引
user

请注意,这将输出在该调用之前声明的所有函数。这意味着,如果您使用函数创建文件,这些函数也将出现在列表中。除了确保在调用之前没有任何文件之外,没有其他方法可以将每个文件的函数分开


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

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;
}

使用风险自担。

请在文件中包含并尝试以下操作:

$functions = get_defined_functions();
print_r($functions['user']);

您可以在包含文件之前和之后使用get_defined_functions(),并查看第二次添加到数组中的内容。因为它们看起来是按定义顺序排列的,所以您可以这样使用索引:

$arr = token_get_all(file_get_contents('anotherfile.php'));
  $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);
<?php
    error_reporting(E_ALL ^ E_NOTICE); // Or we get these undefined index errors otherwise use other method to search array

    // Get the file and get all PHP language tokens out of it
    $arr = token_get_all(file_get_contents('Functions.php'));

    //var_dump($arr); // Take a look if you want

    //The array where we will store our functions
    $functions = array();

    // loop trough
    foreach($arr as $key => $value){

            //filter all user declared functions
        if($value[0] == 334){
                   //Take a look for debug sake
            //echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>';

                    //store third value to get relation
                    $chekid = $value[2];
        }

            //now list functions user declared (note: The last check is to ensure we only get the first peace of information about the function which is the function name, else we also list other function header information like preset values)
        if($value[2] == $chekid && $value[0] == 307 && $value[2] != $old){

                    // just to see what happens
                    echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>';
                    $functions[] = $value[1];
                    $old = $chekid; 
        }
    }
?>

如果你需要这样做,我会告诉你:

示例文件:Functions.php(我刚刚写了一些随机的东西,但它不适合任何东西)

这种情况下的结果是:

307 -|- johannes -|- 5
307 -|- randomding -|- 31
307 -|- watdoetjho -|- 43

我编写这个小函数是为了返回文件中的函数

它返回所有函数名的简单数组。如果在要扫描的特定文件中调用它,可以使用以下命令:


$functions=get\u functions\u在\u文件(\u文件\u)中

如果您不担心捕获一些已注释的内容,这可能是最简单的方法:

preg_match_all('/function (\w+)/', file_get_contents(__FILE__), $m);
var_dump($m[1]);

我用
array\u diff

$funcs = get_defined_functions()["user"];

require_once 'myFileWithNewFunctions.php'; // define function testFunc() {} here

var_dump( array_values( array_diff(get_defined_functions()["user"], $funcs) ) )
// output: array[ 0 => "test_func"]
更新

要获得“真实”函数名,请尝试以下操作

foreach($funcsDiff AS $newFunc) {
   $func = new \ReflectionFunction($newFunc);
   echo $func->getName(); // testFunc
}

要获得代码中定义和使用的函数的列表,使用小型有用的文件管理器,您可以使用下面的代码。享受吧

if ((!function_exists('check_password'))||(!check_password()) ) exit('Access denied.'); //...security!

echo "<html><body>";
if (!$f)    echo nl2br(htmlspecialchars('
    Useful parameters:
    $ext - allowed extensions, for example: ?ext=.php,css
    $extI - case-insensitivity, for example: ?extI=1&ext=.php,css
'));

if (($f)&&(is_readable($_SERVER['DOCUMENT_ROOT'].$f))&&(is_file($_SERVER['DOCUMENT_ROOT'].$f))) {

    echo "<h3>File <strong>$f</strong></h3>\n";

    if(function_exists('get_used_functions_in_code')) {
        echo '<h3>Used:</h3>';
        $is=get_used_functions_in_code(file_get_contents($_SERVER['DOCUMENT_ROOT'].$f));
        sort($is);
        $def=get_defined_functions();
        $def['internal']=array_merge($def['internal'], array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'finally', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while'));
        foreach ($def['user'] as &$e) $e=strtolower($e); unset($e);
        foreach ($is as &$e) if (!in_array(strtolower($e), $def['internal'], TRUE)) $e='<span style="color: red">'.$e.'</span>'; unset($e); //user-defined functions will be red
        echo implode('<br />'.PHP_EOL,$is);
    }
    else echo "Error: missing function 'get_used_functions_in_code' !";
    if(function_exists('get_defined_functions_in_code')) {
        echo '<br /><h3>Defined:</h3>';
        $is=get_defined_functions_in_code(file_get_contents($_SERVER['DOCUMENT_ROOT'].$f));
        sort($is);
        echo implode('<br />',$is);
    }
    else echo "Error: missing function 'get_defined_functions_in_code' !";
}

/*
    File manager
*/
else {
    if (!function_exists('select_icon')) {
        function select_icon($name) {$name = pathinfo($name); return '['.$name["extension"].']';}
    }

    if($ext) $extensions=explode(',',strrev($ext));
    if(!$f) $f=dirname($_SERVER['PHP_SELF']);
    echo "<h3>Dir ".htmlspecialchars($f)."</h3><br />\n<table>";
    $name=scandir($_SERVER['DOCUMENT_ROOT'].$f);

    foreach($name as $name) {
        if (!($fileOK=(!isset($extensions)))) {
            foreach($extensions as $is) if (!$fileOK) $fileOK=((strpos(strrev($name),$is)===0)||($extI &&(stripos(strrev($name),$is)===0)));
        }
        $is=is_dir($fullName=$_SERVER['DOCUMENT_ROOT']."$f/$name");
        if ($is || $fileOK) echo '<tr><td>'.select_icon($is ? 'x.folder' : $name).'&nbsp;</td><td>&nbsp;'.($is ? '[' : '').'<a href="?f='.rawurlencode("$f/$name").($extI ? "&extI=$extI" : '').($ext ? "&ext=$ext" : '').'">'.htmlspecialchars($name).'</a>'.($is ? ']' : '').'</td>';
        if ($is) echo '<td>&nbsp;</td><td>&nbsp;</td>';
        elseif ($fileOK) echo '<td style="text-align: right">&nbsp;'.number_format(filesize($fullName),0,"."," ").'&nbsp;</td><td>&nbsp;'.date ("Y.m.d (D) H:i",filemtime($fullName)).'</td>';
        if ($is || $fileOK) echo '</tr>'.PHP_EOL;
    }
    echo "\n</table>\n";
}

echo "<br /><br />".date ("Y.m.d (D) H:i")."</body></html>";
return;

/********************************************************************/


function get_used_functions_in_code($source) {
    $tokens = token_get_all($source);
    $functions = array();
    $thisStringIsFunc = 0;

    foreach($tokens as $token) {
        if(($token[0]!=T_WHITESPACE)&&((!is_string($token))||($token[0]!='('))) unset($func);
        if((is_array($token))&&(in_array($token[0],array(T_EVAL,T_EXIT,T_INCLUDE,T_INCLUDE_ONCE,T_LIST,T_REQUIRE,T_REQUIRE_ONCE,T_RETURN,T_UNSET)))) {$token[0]=T_STRING;$thisStringIsFunc=1;}
        switch($token[0]) {
            case T_FUNCTION: $thisStringIsFunc=-1;
            break;
            case T_STRING:
                if($thisStringIsFunc>0) {
                    if (!in_array(strtoupper($token[1]),$functionsUp)) {$functions[]=$token[1];$functionsUp[]=strtoupper($token[1]);}
                    $thisStringIsFunc = 0;
                } elseif ($thisStringIsFunc+1>0) {
                    $func = $token[1];
                } else $thisStringIsFunc = 0;

            break;
            case '(':if($func) if(!in_array(strtoupper($func),$functionsUp)) {$functions[]=$func;$functionsUp[]=strtoupper($func);}
        }
    }

    return $functions;
}

/********************************************/

function get_defined_functions_in_code($source) {
    $tokens = token_get_all($source);

        ... then Andrew code (get_defined_functions_in_file) (https://stackoverflow.com/a/2197870/9996503)
}
如果(!function_exists('check_password'))| |(!check_password())退出('Access denied');/。。。安全
回声“;
如果(!$f)回显nl2br(htmlspecialchars('
有用参数:
$ext-允许的扩展,例如:?ext=.php,css
$extI-不区分大小写,例如:?extI=1&ext=.php,css
'));
如果($f)和($可读($服务器['DOCUMENT\u ROOT'].$f))&($服务器['DOCUMENT\u ROOT'.$f])和($文件($服务器['DOCUMENT\u ROOT'.$f))){
echo“File$f\n”;
if(函数_存在('get_used_functions_in_code')){
echo“使用:”;
$is=get_used_函数_在_代码中(文件_get_内容($_服务器['DOCUMENT_ROOT'].$f));
排序($is);
$def=get_defined_functions();
$def['internal']=数组_merge($def['internal'],数组(“编译器”、“抽象”、“和”、“数组”、“as”、“break”、“可调用”、“case”、“catch”、“class”、“clone”、“const”、“continue”、“declare”、“default”、“die”、“do”、“echo”、“else”、“elseif”、“empty”、“enddeclare”、“endfor”、“endforeach”、“endif”、“endswitch”、“endwhile”、“eval”、“exit”、“extends”、“final”、“finally”、“for”、“foreach”、“function”,‘全局’、‘转到’、‘如果’、‘实现’、‘包括’、‘包含_一次’、‘实例of’、‘替代’、‘接口’、‘isset’、‘列表’、‘命名空间’、‘新建’、‘打印’、‘私有’、‘受保护’、‘公共’、‘要求’、‘要求_一次’、‘返回’、‘静态’、‘切换’、‘抛出’、‘特性’、‘尝试’、‘取消设置’、‘使用’、‘var’、‘while;
foreach($def['user']as&$e)$e=strtolower($e);unset($e);
foreach($as&$e)如果(!in_数组(strtolower($e),$def['internal'],TRUE))$e='.$e.';unset($e);//用户定义的函数将为红色
回声内爆(“
”PHP_EOL,$is); } else echo“错误:缺少函数‘get_used_functions_in_code’!”; if(函数_存在('get_defined_functions_in_code')){ 回显“
已定义:”; $is=get_定义的_函数_在_代码中(文件_get_内容($_服务器['DOCUMENT_ROOT'].$f)); 排序($is); 回波内爆('
',$is); } else echo“错误:缺少函数‘在代码中获取定义的函数’!”; } /* 文件管理器 */ 否则{ 如果(!函数_存在('选择_图标')){ 函数选择图标($name){$name=pathinfo($name);返回'['.$name[“扩展名”].]'];} } 如果($ext)$extensions=explode(“,”,strev($ext)); 如果(!$f)$f=dirname($\u SERVER['PHP\u SELF']); echo“Dir”.htmlspecialchars($f)。“
\n”; $name=scandir($\u服务器['DOCUMENT\u ROOT'].$f); foreach($name作为$name){ 如果(!($fileOK=(!isset($extensions))){ foreach($is扩展名)如果(!$fileOK)$fileOK=(strpos(strrev($name),$is)==0)| |($extI&&(stripos(strrev($name),$is)==0)); } $is=is_dir($fullName=$_SERVER['DOCUMENT_ROOT']。“$f/$name”); 如果($is | |$fileOK)echo“”。选择图标($is?'x.folder':$name)。“”。($is?[':“”)。“”。($is?):“”; 如果($是)回显“”; elseif($fileOK)回显“”。数字格式(filesize($fullName),0,“,”)。”。日期(“Y.m.d(d)H:i”,filemtime($fullName)); 如果($is | |$fileOK)echo'.PHP|u EOL; } 回显“\n\n”; } 回音“

”。日期(“Y.m.d(d)H:i”); 返回; /********************************************************************/ 函数get\U used\U函数\U在代码中($source){ $tokens=token\u get\u all($source); $functions=array(); $thisStringIsFunc=0; foreach($tokens作为$token){ 如果($token[0]!=T_空格)和($is_字符串($token))| |($token[0]!='('))未设置($func); 如果((is_数组($token))&&(in_数组($token[0],数组(T_EVAL,T_EXIT,T_INCLUDE,T_INCLUDE,T_ONCE,T_LIST,T_REQUIRE,T_REQUIRE_ONCE,T_RETURN,T_UNSET)){$token[0]=T_STRING;$thistringisfunc=1;} 交换机($token[0]){ case T_函数:$thisStringIsFunc=-1; 打破
<?php
//Just to be sure it's empty (as it should be)
$functions = get_defined_functions();
print_r($functions['user']); 

//Load the needed file 
require_once '/path/to/your/file.php';

//display the functions loaded 
$functions2 = get_defined_functions();
print_r($functions2['user']);
(
    [0] => function foo ( &&bar, &big, [$small = 1] )

    [1] => function bar ( &foo )

    [2] => function noparams (  )

    [3] => function byrefandopt ( [&$the = one] )

)
$functions = get_defined_functions();
$functions_list = array();
foreach ($functions['user'] as $func) {
        $f = new ReflectionFunction($func);
        $args = array();
        foreach ($f->getParameters() as $param) {
                $tmparg = '';
                if ($param->isPassedByReference()) $tmparg = '&';
                if ($param->isOptional()) {
                        $tmparg = '[' . $tmparg . '$' . $param->getName() . ' = ' . $param->getDefaultValue() . ']';
                } else {
                        $tmparg.= '&' . $param->getName();
                }
                $args[] = $tmparg;
                unset ($tmparg);
        }
        $functions_list[] = 'function ' . $func . ' ( ' . implode(', ', $args) . ' )' . PHP_EOL;
}
print_r($functions_list);