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

から関数名を取得した場合は、残りの作業にReflection APIget_defined_functionsを使用することを検討してください。

例:

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();
}
于 2010-04-19T10:27:10.573 に答える
1

Zend_Reflection http://framework.zend.com/manual/en/zend.reflection.htmlを試す

于 2010-04-19T10:31:15.027 に答える