How to find annotations in a PHP5 object?

23,893

Solution 1

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

Solution 2

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

Share:
23,893

Related videos on Youtube

johnnietheblack
Author by

johnnietheblack

im a manic creatician

Updated on June 30, 2020

Comments

  • johnnietheblack
    johnnietheblack almost 4 years

    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
     */
    
  • johnnietheblack
    johnnietheblack over 12 years
    If there are multiple comments in the file, will it grab them all?
  • MightyE
    MightyE over 12 years
    ->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.
  • Slawek
    Slawek over 12 years
    @johnnietheblack you can use php.net/manual/pl/class.reflectionmethod.php - to grab comment only for specified method.
  • johnnietheblack
    johnnietheblack over 12 years
    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...
  • Robik
    Robik over 12 years
    @johnnietheblack You can loop class methods using getMethods which returns array of ReflectionMethod objects, which you can to use get functions annotations.
  • Daniel W.
    Daniel W. almost 9 years
    doctrine/annotations is most popular
  • kmuenkel
    kmuenkel about 6 years
    @DanFromGermany, Doctrine\Common\Annotations\AnnotationReder::getClassAnnotat‌​ions() 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?