php怎样获取列表数据,如何从PHP文件中获取已声明函数及其数据的列表?

我需要从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();

}

标签:declare,list,get,php,function

来源: https://codeday.me/bug/20191210/2099361.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值