25

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
 */
dreftymac
  • 31,404
  • 26
  • 119
  • 182
johnnietheblack
  • 13,050
  • 28
  • 95
  • 133

2 Answers2

53

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

Luke
  • 20,878
  • 35
  • 119
  • 178
Robik
  • 6,047
  • 4
  • 31
  • 41
  • If there are multiple comments in the file, will it grab them all? – johnnietheblack Mar 16 '12 at 18:31
  • `->getDocComment()` just gets the doc comment associated with the object you're examining (the docblock comment immediately preceding that thing's declaration). You can also get doc comments on objects, classes, methods, functions, and properties. – MightyE Mar 16 '12 at 18:33
  • 2
    @johnnietheblack you can use http://php.net/manual/pl/class.reflectionmethod.php - to grab comment only for specified method. – Slawek Mar 16 '12 at 18:34
  • Ahhhh, cool...so I can use the ReflectionClass to grab the doccomment for the class, and then run through it's methods for their comments... – johnnietheblack Mar 16 '12 at 18:35
  • 3
    @johnnietheblack You can loop class methods using [`getMethods`](http://www.php.net/manual/en/reflectionclass.getmethods.php) which returns array of ReflectionMethod objects, which you can to use get functions annotations. – Robik Mar 16 '12 at 18:40
10

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

Slawek
  • 583
  • 3
  • 9
  • 1
    [`doctrine/annotations`](https://github.com/doctrine/annotations) is most popular – Daniel W. Aug 31 '15 at 09:58
  • 1
    @DanFromGermany, `Doctrine\Common\Annotations\AnnotationReder::getClassAnnotations()` seems to explicitly ignore things like `@package` and `@method`. I've also never seen so many usages of `private` and `final` preventing any possible override of this limitation. Is there a way around this? – kmuenkel Apr 25 '18 at 17:50