3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * composer require nikic/php-parser */ require __DIR__ . '/vendor/autoload.php'; use PhpParser\ParserFactory; /** * 获取调用函数的参数 * * @param array $backtrace debug_backtrace * @param string $func 要查找的函数名字 * * @return array 返回调用的参数,如果是变量,就返回变量名,如果不是变量是值,就返回序列号,从参数索引 0 开始编号 */ function getCallFuncArgs(array $backtrace, string $func): array { // 获取调用栈中第一个 $caller = array_shift($backtrace); // 取出文件 $file = $caller['file']; // 创建解析器 $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); $code = file_get_contents($file); // 解析代码 $ast = $parser->parse($code); $nodeFinder = new \PhpParser\NodeFinder(); // 查找所有的函数调用 $nodes = $nodeFinder->findInstanceOf($ast, \PhpParser\Node\Expr\FuncCall::class); $argList = []; foreach ($nodes as $node) { // 找到函数名跟要查找的一致的 if (($node->name->parts[0] ?? null) === $func) { // 创建索引值 $i = 0; // 遍历所有参数 foreach ($node->args as $arg) { // 如果是变量,就取变量名 if ($arg->value instanceof \PhpParser\Node\Expr\Variable) { $argList[] = $arg->value->name; } else { // 否则就编号 $argList[] = '#' . $i; } $i++; } } } return $argList; } function testA() { // 调用 $keys = getCallFuncArgs(debug_backtrace(), __FUNCTION__); // 填充一个关联数组,创建关系 $combine = array_combine($keys, func_get_args()); var_dump($combine); } $a = 1; $b = 2; $c = 2; testA($a, $b, 1, 2, 3, 4, $c);

preferences:
56.4 ms | 408 KiB | 5 Q