How to get a list of declared functions with their data from a php file?

I need to get a list of functions with their contents (and not just the function name) from a php file. I tried to use regex, but it has many limitations. it does not analyze all types of functions. for example, it fails if the function has if statements for the loop as well.

in detail: I have about 100 included files. each file has a number of declared functions. some files are duplicated in other files. so I want to get a list of all functions from a specific file, and then put this list inside an array, then I will use a unique array to remove duplicates. I read about the tokenizer, but I really don't know how to get it to capture the declared function with its data. all i have is:

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

, . . ?

.

+3
2

get_defined_functions, Reflection API .

:

include 'file-with-functions.php';
$reflector = new ReflectionFunction('foo'); // foo() being a valid function
$body = array_slice(
    file($reflector->getFileName()), // read in the file containing foo()
    $reflector->getStartLine(), // start to extract where foo() begins
    $reflector->getEndLine() - $reflector->getStartLine()); // offset

echo implode($body);

@nunthrey , Zend_Reflection, : , . Zend_Reflection:

$reflector = new Zend_Reflection_File('file-with-functions.php');
foreach($reflector->getFunctions() as $fn) {
    $function = new Zend_Reflection_Function($fn->name);
    echo $function->getContents();
}
+2

Source: https://habr.com/ru/post/1741754/


All Articles