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 */
Annotations can be placed in classes, methods, properties and functions. PHP offers only a single form of such metadata - doc-comments. In userland, there exist some annotation reader libraries like Doctrine Annotations which is widely used for eg. to express object-relational mapping metadata.
PHP annotations are basically metadata which can be included in the source code and also in between classes, functions, properties and methods. They are to be started with the prefix @ wherever they are declared and they indicate something specific.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With