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
Related videos on Youtube
Comments
-
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 */
-
Gordon over 12 yearspossible duplicate of stackoverflow.com/search?q=annotation+parser+php
-
leyou about 10 yearsWhy not using a library like doctrine annotations?
-
-
johnnietheblack over 12 yearsIf there are multiple comments in the file, will it grab them all?
-
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 over 12 years@johnnietheblack you can use php.net/manual/pl/class.reflectionmethod.php - to grab comment only for specified method.
-
johnnietheblack over 12 yearsAhhhh, 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 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. almost 9 years
doctrine/annotations
is most popular -
kmuenkel about 6 years@DanFromGermany,
Doctrine\Common\Annotations\AnnotationReder::getClassAnnotations()
seems to explicitly ignore things like@package
and@method
. I've also never seen so many usages ofprivate
andfinal
preventing any possible override of this limitation. Is there a way around this?