Documenting your PHP code

Code documentation

PHP 5 comes with a pretty powerful API built-in called Reflection, which you can use to document your source code for your newly appointed colleagues and partners. All you need is to follow a few guidelines just so Reflection will be able to reformat it for you.

Say for example we have this piece of function:

/**
    For testing purpose. Returns "Hi Full Name", or simply "Hi First Name".
*/
function hello_world($first_name, $last_name='')
{
    return "Hi $first_name $last_name";
}

Notice how the comments are written. It starts with /** and ends with */, and it’s placed right above the function name. That is all we need to follow.

The next step is to write the documentation generator. Say we use the following example :

$my_function = 'hello_world';
$f = new ReflectionFunction($my_function);
foreach($f->getParameters() as $parameter)
{
    $color = $parameter->isOptional() ? 'red' : 'blue';
    $parameter_list[] = '<span style="color:'.$color.'">'.$parameter->name.'</span>';
}
$description      = trim($f->getDocComment(), '*/');
$total_parameters = count($args);
$parameter_list   = implode(', ', $parameter_list);
echo <<<EOF
<pre>
    Function name   = $my_function
    Description     = $description
    # of parameters = $total_parameters
    Parameter list  = $parameter_list
</pre>
EOF;

Put the generator and hello_world() in the same file, then execute it on a browser. The output should be:

    Function name   = hello_world
    Description     = For testing purpose. Returns "Hi Full Name", or simply "Hi First Name".
    # of parameters = 2
    Parameter list  = first_name, last_name

Add a little bit of makeup, and extending with get_defined_functions(), we could produce something equivalent of the top-most screenshot.

Leave a Reply

Your email address will not be published. Required fields are marked *