Introduction to PhpDoc

If you’ve ever tried to read code written by someone other than yourself (who hasn’t?), you know it can be a daunting task. A jumble of “spaghetti code” mixed with numerous oddly named variables makes your head spin. Does this function expect a string or an array? Does this variable store an integer or an object? After countless hours of following the threads of code and trying to understand what each bit does, it’s not uncommon to give up and just rewrite the whole thing from scratch – a task that wastes far too much of your precious time.

PhpDoc, short for PhpDocumentor, is a powerful tool that allows you to easily document your code via specially formatted comments. The documentation will be available not only in the source code, but also in professional documentation extracted using either the web or command-line interface. The result can be in various formats such as HTML, PDF, and CHM. Additionally, many IDEs that provide code-completion can parse PhpDoc comments and provide useful features such as type-hinting. By using PhpDoc, you can make it easy for others (and yourself) to understand your code – weeks, months, and even years after you’ve written it.

The easiest way to install PhpDoc is with PEAR. Of course, before you can do so you must have PEAR installed. If you don’t, follow the instructions at pear.php.net/manual/en/installation.php.

In this article I’ll show you how to use PhpDoc to generate gorgeous and user-friendly documentation from beginning to end.

DocBlocks

A DocBlock is a multi-line C-style comment used to document a block of code. It begins with /** and has an asterisk at the start of each line. Here’s an example:

<?php
/**
 * Calculates sum of squares of an array
 *
 * Loops over each element in the array, squares it, and adds it to 
 * total. Returns total.
 * 
 * This function can also be implemented using array_reduce();
 * 
 * @param array $arr
 * @return int
 * @throws Exception If element in array is not an integer
 */
function sumOfSquares($arr) {
    $total = 0;
    foreach ($arr as $val) {
        if (!is_int($val)) {
            throw new Exception("Element is not an integer!");
        }
        $total += $val * $val;
    }
    return $total;
}

DocBlocks consist of three sections: short description, long description, and tags. All three sections are optional.

The short description is a succinct description terminated by either a new-line or a period. PhpDoc’s parsing routines are smart; it will only end the short description if the period is at the end of a sentence.

The long description is where the bulk of the documentation goes; it can be multi-line and as long you wish.

Both the long and short descriptions may contain certain HTML elements for formatting. HTML tags that aren’t supported will be displayed as plain text. PhpDoc can generate the documentation in multiple formats, though, so the HTML tags aren’t necessarily rendered as they would in an HTML file; the actual formatting depends on the generated file format. If you need to display an HTML tag as text, use double brackets. For example:

<?php
/**
 * Here an example of the italics tag: <<i>>Hello, world!<<i>>
 */

The tags section of a DocBlock contains any number of special tags denoted by the @ symbol. The tags are used to specify additional information, such as the expected parameters and their type. Most tags must be on their own line, with the exception of certain tags which may be inline. Inline tags are surrounded with curly braces and may be in both the long and short description. For a full list of tags, check out the relevant PhpDoc documentation.

If you need to start a line with the @ symbol but you don’t want it to be interpreted as a tag, you can escape it with a backslash.

PhpDoc will automatically recognize textual lists in the long and short descriptions and it will parse them. However, it won’t parse nested lists correctly. If you want to use nested lists, use the HTML tags. Here is an example to illustrate what I mean:

<?php
/**
 * Example of using lists
 * 
 * PhpDoc will parse this list correctly: 
 * - Item #1
 * - Item #2
 * - Item #3
 * 
 * But not this list:
 * - Item 1
 *   - Item 1.1
 *   - Item 1.2
 * - Item 2
 * 
 * Use this instead for a nested list:
 * <ul>
 *   <li>Item 1</li>
 *   <ul>
 *     <li>Item 1.1</li>
 *     <li>Item 1.2</li>
 *   </ul>
 *   <li>Item 2</li>
 * </ul>
 */

Packages

PhpDoc packages are used to group related code elements in the generated documentation. You can specify packages for files and classes and the documented code they contain will inherit the package from them. To specify a package, set the @package tag in a file-level or class-level DocBlock (file-level and class-level DocBlocks will be discussed further is the following section). A package name may contain letters, numbers, dashes, underscores, and square brackets (“[" and "]“).

Here is an example of defining a file’s package:

<?php
/**
 * This is a file-level DocBlock
 * 
 * @package Some_Package
 */

If you have multiple levels of packages and sub-packages, you can define a sub-package with the @subpackage tag. Here is an example:

<?php
/**
 * This is a class-level DocBlock
 * 
 * @package    Some_Package
 * @subpackage Other
 */
class SomeClass {
}

If a file or class doesn’t specify a package it will be set to the default package, “default”. You can specify a different package to be used by default when generating the documentation via the -dn command-line option.

What Can I Document?

Not all code elements can be documented with DocBlocks. Here is a list of code elements that may be documented:

  • Files
  • Classes
  • Functions and methods
  • Class properties
  • Global variables
  • include()/require()
  • define()

All of these elements can use certain common tags, but each has tags that are specific to that element. I’ll go over a few of the elements and the tags normally used to document them.

Files

File-level DocBlocks are used to document the contents of a file. It is highly recommended to include a file-level DocBlock in every file you document, and in fact PhpDoc will display a warning if one is not found when generating documentation.

Most elements are documented by placing a DocBlock before the element, but files are an exception (since you can’t write anything before a file). File-level DocBlocks are placed on the first line of the file.

A file-level DocBlock usually contains the tags @package, @subpackage, @license, and @author. The @package and @subpackage tags were discussed earlier. The @license tag is used to specify a URL to an external license that covers your code. The tag must contain the URL to the license and optionally a title. The @author tag is used to specify the author of the file. It must contain the author’s name and optionally an email address in angle brackets.

Unlike most elements, a file-level DocBlock must contain a @package tag in order to be parsed properly.

Here is a complete example of a file-level DocBlock:

<?php
/**
 * This file contains common functions used throughout the application.
 *
 * @package    MyProject
 * @subpackage Common
 * @license    http://opensource.org/licenses/gpl-license.php  GNU Public License
 * @author     Moshe Teutsch <moteutsch@gmail.com>
 */

Classes

A class-level DocBlock is placed before a class definition and should describe the meaning of the class. Like file-level DocBlocks, class-level DocBlocks usually contain the tags @package, @subpackage, and @author. Here is an example:

<?php
/**
 * An example class
 *
 * The class is empty for the sake of this example.
 *
 * @package    MyProject
 * @subpackage Common
 * @author     Moshe Teutsch <moteutsch@gmail.com>
 */
class Example {
}

Functions and methods

Functions and methods are documented identically in PhpDoc. (For those who may not be familiar with the terminology, a method is just a function within a class.) Functions and methods usually contain the @param and @return tags in their DocBlocks. The @param tag is used to document the expected type of a parameter. It contains three sections: the parameter, the data type, and an optional description. The @return tag is used to document the return type. It contains two sections: the data type and an optional description. In both tags, the data type can be either a valid PHP data type, a class name, or “mixed”. It can also contain multiple options separated by a pipe.

<?php
/**
 * Finds and returns user by ID or username
 *
 * @param int|string $user Either an ID or a username
 * @param PDO $pdo A valid PDO object
 * @return User Returns User object or null if not found
 */
function getUser($user, PDO $pdo)
{
    // ...
    if ($isFound) {
        return new User(...);
    }
    return null;
}

Generating Documentation

Once you’ve documented your PHP code, you’ll want to generate user-friendly documentation from it. To do so, run the PhpDoc command-line tool.

moteutsch@vivaldi:~$ phpdoc -d /path/to/files/ -t /path/to/docs/ -ti 'Documentation Title' -dn 'Default Package' -o HTML:frames:default

The -d option specifies a comma-separated list of directories containing files to document, and -t the path to generated docs. -ti is used to specify the project title, and -dn to set the default package name. Finally, -o specifies the documentation format. PhpDoc has a wide selection of formats to choose from. A full list is available on the PhpDoc website.

You can find out more about the command-line tool by executing the help command as follows:

moteutsch@vivaldi:~$ phpdoc -h

Once you run the command, the documentation path you specified should contain the generated docs.

For those of you who aren’t comfortable using the command-line interface, PhpDoc also has a web interface available. It’s outside of this articles scope to discuss it at length, but you can read more about it on PhpDoc’s official website, phpdoc.org.

Summary

In this article I’ve given you a first look at PhpDoc and its many powerful features. I have explained the purpose of DocBlocks and their components; I have shown you how to organize your documentation using packages; I have explained which code elements can be documented and some common examples of doing so; finally, I have shown you how to generate documentation from your source code. I highly recommend that you start using PhpDoc in your own projects, if even only to document the most important parts. It is very straight-forward and will save you and your co-workers countless hours of nail-biting and hair-pulling.

Image via Zadorozhnyi Viktor / Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • GaryJ

    phpDocumentor as a project is dead, and has been for a while. However, the same documentation and tags that you outline here (and more) can be used with DocBlox, a similar tool as phpDocumentor but one that also supports PHP 5.3 features, allows easier customising of templates, and parses and transforms documentation far quicker and with lower memory than phpDocumentor. Well worth checking out: http://docblox-project.org

  • http://harikt.com/blog Hari K T

    Nice article Moshe Teutsch.
    I also agree with GaryJ about the docblox project. The fact is, everything that Moshe Teutsch has expressed will work on docblox too. Docblox has almost the same syntax.

  • Tjorriemorrie

    Nice article. Also agree with above comments; kind of a waste to support something that’s dead. Like digging up a grave = bad idea.

  • Ed

    The strange thing with recommending phpdoc is that it isn’t even able to generate documentation for 5.3 projects if they use a single Closure.

    With projects like phpdox ( https://github.com/theseer/phpdox ) and docblox ( http://docblox-project.org/ ).

    There tools also allow for less wasteful param tags (where there is no need to restate names and typehints again in the docs and risk inconsistency)

  • http://www.carsbiz.net CarsBiz

    I’ve spent a long time going through other people’s PHP code and I can tell you that something like this would make my life a great deal easier (even if this particular project is dead). I will certainly be looking into a similar solution.

  • http://www.docblox-project.org Mike van Riel

    phpDocumentor might not support everything that you need and is currently not actively maintained. DocBlox (http://www.docblox-project.org) tries to fill a gap here by providing faster, less memory intensive processing and PHP 5.3+ compatibility.

  • Shadow Caster

    Shouldn’t the data type and variable name of the @param comments be the other way round in the Functions and Methods section?

    • Jaco Nel

      +1. We follow the following convention:
      @param string $sName The user’s first name

  • Andrea

    What about Doxygen? None named it, and as far as I know it has support for PHP 5.3 (since last versions), it’s widely used, multiplatform, using almost same syntax of phpDoc (which inspires itself to JavaDoc). It may be used also for other languages. Anyway a look at http://www.doxygen.org

  • Jaco Nel

    Since PHPDocument is dead and does not support 5.3 many developers are starting to move over to DocBlox. I found this article highlighting a few of the nice DocBlox features http://mwop.net/blog/265-Using-DocBlox.

    You can also find a basic comparison of the different tools at http://blog.liip.ch/archive/2011/07/26/phpdoc-compilers-and-inheritdoc.html.

  • http://www.web3box.com Daniel Gheorghe

    I’ve read the article and all the comments and they convinced me to do some research on that but in the end I believe that any of the options you’ve talked about will help my developers. The only real downside that I see regarding PHPDocument is its lack of support for 5.3… Anyway thank you guys for this great post… code documentation was a real issue in my company.

  • http://www.nine10.ca/ Richard Podsada

    Has anybody here ever worked with ApiGen? I first heard of this while reading the development roadmap for NetBeans 7.2 (they’ve added support in some of the latest builds.) I took a quick peek and it looks like a pretty nice system. Creates nice clean looking documentation and if it’s integrated into NetBeans, all the better. I haven’t tried it yet but I might give it a fly to see how it does. http://apigen.org/. Thanks for the links to DoxyGen nd DocBlox too, I’ll check those out!

  • Daniel

    I dont think PHPDocumentor is dead: http://www.phpdoc.org/
    Also, I am sure it has just merged with DocBlox

    • Jaco Nel

      At time of my comment, phpdocumentor’s announcement of merging with DocBlox was not yet out. PhpDocumentor has taken over DoxBlox and formed PHPDocumentor2. PHPDocumentor2 has strong support for php5.3

  • Raheel Dharolia

    Yes it’s true. DocBlox has merged with phpDocumentor to become phpDocumentor2. Please come visit http;//www.phpdoc.org

  • http://github-phpdoc.israelviana.es Isra

    Hi! I developed a service for generating phpDocs in the cloud for GitHub repositories… and the best part is that the docs are generated on each push to the repo!
    If you like the idea you can give it a try at http://github-phpdoc.israelviana.es ¡I’d appreciate very much the feedback!