Introduction to PhpDoc

Moshe Teutsch
Moshe Teutsch
Published in
PHP·
·Updated:

Share this article

SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools

7 Day Free Trial. Cancel Anytime.

Key Takeaways

  • PhpDoc, or PhpDocumentor, is a tool that helps developers to document their code through specially formatted comments. It generates documentation in various formats such as HTML, PDF, and CHM, which can be extracted via the web or command-line interface.
  • PhpDoc uses DocBlocks, multi-line C-style comments, to document blocks of code. DocBlocks consist of three optional sections: short description, long description, and tags. Tags are special elements denoted by the @ symbol, used to specify additional information about the code.
  • PhpDoc packages are used to group related code elements in the generated documentation. They can be specified for files and classes using the @package and @subpackage tags in a file-level or class-level DocBlock.
  • PhpDoc can document various code elements including files, classes, functions and methods, class properties, global variables, include()/require() and define(). Each of these elements can use certain common tags, but each has tags specific to that element.
  • PhpDoc’s command-line tool is used to generate user-friendly documentation from the documented PHP code. The tool offers a wide selection of formats for the documentation. For those uncomfortable with the command-line interface, PhpDoc also provides a web interface.
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

Frequently Asked Questions (FAQs) about PHPDoc

What is the significance of PHPDoc in PHP programming?

PHPDoc is a documentation tool in PHP programming that allows developers to provide information about the functionality of their code in a standardized format. It is a powerful tool that helps in understanding the code better, making it easier to maintain and debug. PHPDoc comments are written directly in the source code, making them readily available and easy to update. They can describe functions, classes, methods, constants, and more. PHPDoc also supports generating API documentation in HTML format, which can be shared with other developers or end-users.

How do I write a basic PHPDoc comment?

Writing a PHPDoc comment is straightforward. It starts with a “/**” and ends with a “*/”. Inside this, you can include various tags to describe different aspects of your code. For example, the “@param” tag is used to describe a function parameter, and the “@return” tag is used to describe the return value of a function. Here’s an example:

/**
* Calculates the sum of two numbers.
*
* @param int $a The first number.
* @param int $b The second number.
* @return int The sum of the two numbers.
*/
function sum($a, $b) {
return $a + $b;
}

Can I generate documentation from PHPDoc comments?

Yes, one of the key features of PHPDoc is its ability to generate API documentation from your comments. This is done using a tool like phpDocumentor, which scans your source code and generates HTML pages containing your comments and information about your code’s structure. This can be extremely useful for sharing information about your code with other developers or end-users.

What are some common PHPDoc tags and their uses?

PHPDoc supports a wide range of tags to describe different aspects of your code. Some of the most common ones include “@param” (describes function parameters), “@return” (describes the return value of a function), “@var” (describes a variable), “@throws” (indicates the exceptions a function can throw), and “@deprecated” (indicates that a piece of code is deprecated and should not be used).

How can PHPDoc help with code quality and debugging?

PHPDoc can significantly improve code quality and ease the debugging process. By providing detailed information about your code’s functionality, PHPDoc comments make it easier to understand what each part of your code is supposed to do. This can help prevent bugs and make it easier to spot any that do occur. Additionally, many IDEs can use PHPDoc comments to provide autocompletion and other helpful features, further improving your productivity.

Can PHPDoc comments include examples?

Yes, PHPDoc comments can include examples of how to use a function or method. This can be done using the “@example” tag, followed by the path to a file containing the example code. This can be a great way to provide additional context and help other developers understand how to use your code.

How does PHPDoc handle inheritance?

PHPDoc has built-in support for inheritance. If a class extends another class, PHPDoc will automatically include the parent class’s comments in the child class’s documentation, unless the child class has its own comments. This can be a great way to avoid duplicating information and keep your documentation consistent.

Can PHPDoc comments be used with private and protected methods?

Yes, PHPDoc comments can be used with private and protected methods, as well as public ones. However, keep in mind that private and protected methods are not included in the generated documentation by default, as they are not part of the public API. If you want to include them, you’ll need to configure your documentation generator accordingly.

What is the difference between PHPDoc and other documentation tools?

PHPDoc is specifically designed for PHP and supports features specific to the language, such as namespaces and traits. It also supports a wide range of tags to describe different aspects of your code, making it a very flexible tool. Other documentation tools may not have these features, or they may be designed for different programming languages.

How can I get started with PHPDoc?

To get started with PHPDoc, you’ll first need to understand how to write PHPDoc comments. Once you’re comfortable with that, you can start adding them to your code. From there, you can use a tool like phpDocumentor to generate documentation from your comments. Remember, the key to good documentation is to keep it up-to-date and as detailed as possible.

Moshe Teutsch is a freelance web developer and entrepreneur. He specializes in PHP programming and is currently available for hire. In his spare time he enjoys playing chess, singing, writing, reading, philosophizing, and coding in esoteric programming languages.

documentationIntermediate

Share this article

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.