Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Advanced Documentation With Reflection In PHP 5

Reflecting On Your Code

Everyone knows the value of keeping good documentation, but correspondingly everyone hates publishing new documentation as an application evolves.

Reflection is an OOP concept for accessing a script’s extended information; this information is also known as metadata. In other languages like C# there are lots of metadata tools like attributes, XML documentation, manifest files, code regions and the like, however, in PHP there is only one little known trick for including metadata in your application.

This trick relates to the way PHP code is parsed. To understand this trick, you have to first understand the phases of PHP execution under the hood. Explaining this in full is far beyond the scope of this article, however, the basics are as follows.

First, a request is received by the web server and routed to the PHP module. Once the PHP module has received a request, it will find the requested file, and begin the parsing phase. This is all fairly complicated, but to put it simply, the code is run through a part of the Zend Engine called the Zend_Language_Parser.

The result of this phase is a series of objects about every piece of code. They include operational codes, and fortunately for us, one member of this object is the doc_comment.

These objects are then used by php to actually begin compilation, execution and output back to the web server. But all we need know for our purposes is that the doc_comment is not discarded during this parsing operation as one might expect.

So what defines a doc_comment? A doc_comment as PHP defines it is any comment prefixing a class, interface, method or function that begins with a /** and ends with a */.

For example:

Listing 1 listing-1.php
     * This is a doc_comment.
    class someclass
        // this is not a doc comment because
        // it doesn't start with /** and end
        // with */ and doesn't prefix a class,
        // interface, method or function

The above comment is now stored in PHP’s metadata, however, it’s not very useful to us. It isn’t parsible, it doesn’t contain any kind of useful information and it’s certainly not in the valid phpdoc format.

In This Article