Function list of php file

前端 未结 12 1246
南方客
南方客 2020-11-28 14:40

How to get list of functions that are declared in a php file

相关标签:
12条回答
  • 2020-11-28 15:15

    I wrote this small function to return the functions in a file.

    https://gist.github.com/tonylegrone/8742453

    It returns a simple array of all the function names. If you're calling it in the particular file you want to scan, you can just use the following:

    $functions = get_functions_in_file(__FILE__);

    0 讨论(0)
  • 2020-11-28 15:17

    do include to the file and try this :

    $functions = get_defined_functions();
    print_r($functions['user']);
    
    0 讨论(0)
  • 2020-11-28 15:18

    You can use the get_defined_functions() function to get all defined function in your current script.

    See: http://www.php.net/manual/en/function.get-defined-functions.php

    If you want to get the functions defined in another file, you can try using http://www.php.net/token_get_all like this:

    $arr = token_get_all(file_get_contents('anotherfile.php'));
    

    Then you can loop through to find function tokens with the symbols defined. The list of tokens can be found http://www.php.net/manual/en/tokens.php

    0 讨论(0)
  • 2020-11-28 15:18

    To get list of defined and used functions in code, with small useful file manager, you can use code below. Enjoy!

    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)
    }
    
    0 讨论(0)
  • 2020-11-28 15:20

    The simplest thing (after I saw @joachim answer) is to use get_defined_functions and then only watch for the 'user' key (which contains an array of user-defined methods)

    This is the code that helped me solved the problem

    <?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 讨论(0)
  • 2020-11-28 15:21

    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.

    0 讨论(0)
提交回复
热议问题