nikic / PHP-Parser 包的简单实用
解析PHP文件:
<?php require 'vendor/autoload.php'; use PhpParser\ParserFactory; $code = file_get_contents(dirname(__FILE__) . '/src/Aop/Target.php'); $phpFactory = new ParserFactory(); $parser = $phpFactory->create(ParserFactory::PREFER_PHP7); //var_dump($parser->parse($code));die(); foreach ($parser->parse($code) as $k => $v) { if ($v instanceof \PhpParser\Node\Stmt\Namespace_) { echo 'class namespace: ' . join('\\', $v->name->parts), PHP_EOL; foreach ($v->stmts as $kk => $vv) { if ($vv instanceof \PhpParser\Node\Stmt\Use_) { //多个use循环 foreach ($vv->uses as $kkk => $vvv) { echo 'class use: ' . join('\\', $vvv->name->parts), PHP_EOL; echo 'class use alias: ' . $vvv->alias, PHP_EOL; } } elseif ($vv instanceof \PhpParser\Node\Stmt\Class_) {//类内容 echo 'class extends: ' . $vv->extends, PHP_EOL; echo 'class implements: ' . join(',', $vv->implements), PHP_EOL; echo 'class name: ' . $vv->name, PHP_EOL; foreach ($vv->stmts as $kkk => $vvv) {//类属性和方法 if ($vvv instanceof \PhpParser\Node\Stmt\Property) {//属性 foreach ($vvv->props as $kkkk => $vvvv) { echo 'class property name: ' . $vvvv->name, PHP_EOL; echo 'class property value: ' . $vvvv->default->value, PHP_EOL; } } elseif ($vvv instanceof \PhpParser\Node\Stmt\ClassMethod) {//方法 echo 'class method name: ' . $vvv->name->name, PHP_EOL; echo 'classs method returnType: ' . $vvv->returnType, PHP_EOL; foreach ($vvv->params as $kkkk => $vvvv) {//方法参数 echo 'classs method param name: ' . $vvvv->var->name, PHP_EOL; echo 'classs method param default: ' . $vvvv->default, PHP_EOL; } foreach ($vvv->stmts as $kkkk => $vvvv) {//方法返回 echo 'class method return value: ' . $vvvv->expr->value, PHP_EOL; } } } } } } }
执行后:
分情破爱始乱弃,流落天涯思别离。
如花似玉负情意,影如白昼暗自迷。
随风浮沉千叶落,行色匆匆鬓已稀。