I'm using the Reflection API in PHP to pull a DocComment (PHPDoc) string from a method
$r = new ReflectionMethod($object);
$comment = $r->getDocComment();
This will return a string that looks something like this (depending on how well the method was documented)
/**
* Does this great things
*
* @param string $thing
* @return Some_Great_Thing
*/
Are there any built-in methods or functions that can parse a PHP Doc Comment String into a data structure?
$object = some_magic_function_or_method($comment_string);
echo 'Returns a: ', $object->return;
Lacking that, what part of the PHPDoc source code should I be looking at the do this myself.
Lacking and/or in addition to that, is there third party code that's considered "better" at this that the PHPDoc code?
I realize parsing these strings isn't rocket science, or even computer science, but I'd prefer a well tested library/routine/method that's been built to deal with a lot of the janky, semi-non-correct PHP Doc code that might exist in the wild.
I am surprised this wasn't mentioned yet: what about using Zend_Reflection of Zend Framework? This may come in handy especially if you work with a software built on Zend Framework like Magento.
See the Zend Framework Manual for some code examples and the API Documentation for the available methods.
There are different ways to do this:
Let's go for the simple case and assume you have an existing class you want to inspect.
The code would be like this (untested, please forgive me):
Check out
http://pecl.php.net/package/docblock
The docblock_tokenize() function will get you part-way there, I think.
Updated version of user1419445's code. The
DocBlockParser::parse()
method is changed and needs a second context parameter. It also seems to be slightly coupled with phpDocumentor, so for the sake of simplicity I would assume you have Sami installed via Composer. The code below works for Sami v4.0.16As pointed out in one of the answers above, you can use phpDocumentor. If you use composer, then just add "phpdocumentor/reflection-docblock": "~2.0" to your "require" block.
See this for an example: https://github.com/abdulla16/decoupled-app/blob/master/composer.json
For usage examples, see: https://github.com/abdulla16/decoupled-app/blob/master/Container/Container.php
If you're trying to read in the @ tags and their values, then using preg_match would be the best solution.
I suggest you to take a look at http://code.google.com/p/php-annotations/
The code is fairly simple to be modified/understood if needed.