How to find annotations in a PHP5 object?

2019-01-17 07:16发布

I would like to be able to implement custom annotations in my PHP5 objects, and I'd like to learn how the whole process works by building my own parser.

To start, though, I need to know how to FIND the annotations.

Is there a Reflection method that I am missing, or is there another way?

For example, I'd like to be able to find the following annotation in a class:

/**
 * @MyParam: myvalue
 */

2条回答
走好不送
2楼-- · 2019-01-17 07:47

You can do this using ReflectionClass::getDocComment, example:

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

Live demo: http://codepad.viper-7.com/u8bFT4

查看更多
Lonely孤独者°
3楼-- · 2019-01-17 07:48

You can get comment block using getDocComment Reflection object method.

If you don't want to retrieve annotation by hand, you can use Zend Framework Reflection or other existing solution

查看更多
登录 后发表回答