Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find annotations in a PHP5 object?

Tags:

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  */ 
like image 747
johnnietheblack Avatar asked Mar 16 '12 18:03

johnnietheblack


People also ask

Does PHP have annotation?

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.

What are annotations in PHP?

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.


2 Answers

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

like image 149
Robik Avatar answered Oct 09 '22 20:10

Robik


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

like image 41
Slawek Avatar answered Oct 09 '22 18:10

Slawek