Advanced Documentation With Reflection In PHP 5
Extracting Code Comments With The Reflection API
Now you know how metadata is stored, and how to format it. To access metadata, we need to use the Reflection API.
The Reflection API is a series of classes new to PHP 5 which you provide the name of the item you wish to introspect. The class then has a number of methods and properties containing the relevant information.
You can reflect functions with
ReflectionFunction, classes and interfaces with
To reflect a class you simply provide the name as a string to the constructor of
ReflectionClass. We then have a number of properties and methods available, but the one you care about is the
$oClassReflect = new ReflectionClass("classname"); $sDocComment = $oClassReflect->getDocComment();
You now have the doc comment as a string, but it isn’t very useful. To parse the phpdoc style commenting from the comment use a series of string processing functions. Use a few regular expressions to remove the
*‘s and then, normalize the values into an array of lines. Additionally, each line may have multiple successive tabs and these should be treated as a single tab.
$sDocComment = preg_replace("/(^[\\s]*\\/\\*\\*) |(^[\\s]\\*\\/) |(^[\\s]*\\*?\\s) |(^[\\s]*) |(^[\\t]*)/ixm", "", $sDocComment); $sDocComment = str_replace("\r", "", $sDocComment); $sDocComment = preg_replace("/([\\t])+/", "\t", $sDocComment); $aDocCommentLines = explode("\n", $sDocComment);
Next you will want to loop through the resulting array and do some basic parsing. String processing is beyond the scope of this article so I will simply point you to our website and you can look at the working parser in the StormAPI package (