我需要从 php 文件中获取函数列表及其内容(不仅仅是函数名称)。我尝试使用正则表达式,但它有很多限制。它不会解析所有类型的函数。例如,如果函数有 if 和 for 循环语句,它就会失败。
详情: 我有大约 100 个包含文件。每个文件都有许多声明的函数。某些文件具有在其他文件中重复的功能。所以我想要的是从特定文件中获取所有函数的列表,然后将此列表放入一个数组中,然后我将使用唯一数组来删除重复项。我阅读了有关 tokenizer 的信息,但我真的不知道如何让它获取声明的函数及其数据。 我只有这个:
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;
}
不幸的是,这个函数只列出了函数名.. 我需要的是列出整个声明的函数及其结构.. 那么有什么想法吗?
提前致谢..
最佳答案
如果您从 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 suggested ,您还可以使用 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();
}
关于php - 如何从 php 文件中获取已声明函数及其数据的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2666554/