用PHP解析类,函数和参数 [英] Parsing Classes, Functions and Arguments in PHP
问题描述
我想创建一个函数,该函数接收一个参数,该参数保存一个PHP文件的路径,然后解析给定的文件并返回如下内容:
I want to create a function which receives a single argument that holds the path to a PHP file and then parses the given file and returns something like this:
class NameOfTheClass
function Method1($arg1, $arg2, $arg2)
private function Method2($arg1, $arg2, $arg2)
public function Method2($arg1, $arg2, $arg2)
abstract class AnotherClass
function Method1($arg1, $arg2, $arg2)
private function Method2($arg1, $arg2, $arg2)
public function Method2($arg1, $arg2, $arg2)
function SomeFunction($arg1, $arg2, $arg3)
此函数应返回给定文件中存在的所有类,方法和函数,以及所有已定义的标识符(抽象,公共,私有,受保护,静态,扩展,接口等).
This function should return all the classes, methods and function that exist in the given file with all the defined identifiers (abstract, public, private, protected, static, extends, interfaces, ...).
我的第一个强项是使用正则表达式来执行此操作,但是它们在注释时的表现非常差,即:/*此函数返回(max(salary))*/,如果我想适当地支持范围,则变得非常复杂.
My first tought was to use regular expressions to do this, however these behave quite badly with comments, ie: /* this function returns(max(salary)) */ and become quite complex if I want to properly support scopes.
另一种可能的解决方案是使用以下内置的PHP函数:
Another possible solution was to use the following built-in PHP functions:
get_declared_classes
get_declared_interfaces
get_defined_functions
get_class_methods
但是这些函数不允许我查看定义了类/方法/函数的文件,因此它不是很有用.
However these functions don't allow me to see the file where the classes / methods / functions are defined and thus it's not very useful.
我相信Tokenizer扩展程序可以解决我的问题,但是我以前从未使用过此扩展程序.
I believe the Tokenizer extension is the solution for my problem, however I have never used this extension before.
推荐答案
如果您使用的是PHP 5,则 Reflection API 是您的工具.
If you are using PHP 5, the Reflection API is your tool.
示例:
$class = new ReflectionClass("NameOfTheClass");
$methods = $class->getMethods();
foreach($methods as $m) {
print $m->name;
$m->isPrivate() ? print "Private" : print "";
$m->isPublic() ? print "Public" : print "";
$params = $m->getParameters();
foreach($params as $p) {
print $p->getName();
}
}
这篇关于用PHP解析类,函数和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!