4

我需要从 php 文件中获取函数列表及其内容(不仅是函数名)。我尝试使用正则表达式,但它有很多限制。它不会解析所有类型的函数。例如,如果函数有 if 和 for 循环语句,它就会失败。

详细信息:我有大约 100 个包含文件。每个文件都有许多声明的函数。某些文件具有在其他文件中重复的功能。所以我想要的是从特定文件中获取所有函数的列表,然后将此列表放入一个数组中,然后我将使用唯一的数组来删除重复项。我阅读了有关标记器的信息,但我真的不知道如何让它使用其数据获取声明的函数。我只有这个:

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

不幸的是,这个函数只列出了函数名。我需要列出整个声明的函数及其结构。所以有什么想法吗?

提前致谢..

4

2 回答 2

3

If you got the function names from your get_defined_functions, consider using Reflection API for the remaining work.

Example:

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

Like @nunthrey suggested, you can also use Zend_Reflection to get both: the functions in a file and their content. Example with 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();
}
于 2010-04-19T10:27:10.573 回答
1

试试 Zend_Reflection http://framework.zend.com/manual/en/zend.reflection.html

于 2010-04-19T10:31:15.027 回答