如何在PHP5对象中查找注释?

joh*_*ack 20 php parsing annotations docstring

我希望能够在PHP5对象中实现自定义注释,并且我想通过构建自己的解析器来了解整个过程是如何工作的.

但是,首先,我需要知道如何查找注释.

有没有我想念的反射方法,还是有另一种方法?

例如,我希望能够在类中找到以下注释:

/**
 * @MyParam: myvalue
 */
Run Code Online (Sandbox Code Playgroud)

Rob*_*bik 45

您可以使用以下ReflectionClass::getDocComment示例执行此操作:

function getClassAnnotations($class)
{       
    $r = new ReflectionClass($class);
    $doc = $r->getDocComment();
    preg_match_all('#@(.*?)\n#s', $doc, $annotations);
    return $annotations[1];
}
Run Code Online (Sandbox Code Playgroud)

现场演示:http://codepad.viper-7.com/u8bFT4

  • @johnnietheblack您可以使用[`getMethods`](http://www.php.net/manual/en/reflectionclass.getmethods.php)循环类方法,它返回ReflectionMethod对象的数组,您可以使用get函数注释. (3认同)
  • @johnnietheblack您可以使用http://php.net/manual/pl/class.reflectionmethod.php - 仅为指定方法获取注释. (2认同)

Sla*_*wek 9

您可以使用getDocComment Reflection对象方法获取注释块.

如果您不想手动检索注释,可以使用Zend Framework Reflection或其他现有解决方案