Introduction to PHP Coding Standards

5 comments | Posted: 18 April 07 in Tutorials, by Yannick Lyn Fatt

Being the Web Standardistas that we are, it’s all about using best practices and following the specifications proposed by the W3C, but what about us PHP programmers, where are our standards? The purpose of this article is to give an introduction to PHP Coding Standards and a few examples as defined by the PEAR and Zend Groups.

Introduction

Whether you are new to PHP programming or a seasoned veteran you can benefit from following a set of coding standards. When I first started programming in PHP, I gave very little thought to how my code looked. I pretty much just put some code together and as long as it worked I was happy. From project to project, I would notice that the way I named variables and functions would vary. There was no consistency. It wasn’t until recently that I thought to myself, “Surely there must be a set of ‘Best practices’ when writing PHP code.” It was then I stumbled across an interesting presentation by two members of the Zend Company. While the presentation covered more topics, this article will focus on just the Coding Standards.

Apart from PEAR being probably the most popular PHP code repository, the PEAR Coding Standard is the basis for a number of PHP projects such as:

and I’m sure there are many more.

Now let us look at a few examples of the standards in action.

Indentation, Line length and Comments

It is generally recommended that you use spaces for indentation instead of tabs and use 4 spaces for each level of indentation. The purpose of this is for consistency across editors and operating systems. In some editors it is also possible to change it’s preferences/settings to use spaces instead of tabs and tell it the amount of spaces to use when indenting.

You should also try to keep your line lengths to between 75-85 characters maximum for readability purposes.

When doing non-documentation comments, they should be written using the C style comments (/* */) and standard C++ comments (//).

/*
This is a block comment
It can span multiple lines.
This is the third line.
*/

// And this is a single line comment

The use of the Shell/Perl style comments (#) is discouraged.

Naming Conventions

Having consistent naming conventions throughout your code is good practice. Classes should be descriptive and as best as possible abbreviations should not be used. PEAR also recommends using CamelCase with an initial cap and underscores used to logically separate package/folder boundaries. For example:

Zend_Filter_Alpha

So with the class name stated above, the file name mapping would be:

Zend/Filter/Alpha.php

Next are variable names. Variable names are also written in CamelCase, however, the first letter is now lowercase.

$myVariable = 'something';

While constants are all uppercase with an underscore used to separate words.

$MY_CONSTANT = 'something';

Control Structures

As you know control structures include if, while, foreach statements, etc. For structures like these, opening curly brace are kept on the same line as the declaration and the closing curly brace is aligned at the same indent level as the start of the control structure. Also there is usually one space between the control keyword and opening parenthesis and also one space between the closing parenthesis and the opening curly brace.

if (condition) {
    // code...
} else {
    // more code...
}
while (condition) {
    // code...
}

Functions

For functions, the opening curly brace occurs in the line below the function name (“one true brace” form) and there is no space between the opening parenthesis and the function name. Also if the function is a method for a Class it is advised that you state the scope of the function (ie. public, private or protected).

public function myFunction($arg1, $arg='')
{
    //code...
}

Note that arguments that are optional should be placed after those that are required.

PHP Tags

Then there is the matter of whether to use short tags delimit your PHP code. It is recommended that you do it the regular way, as it is the most portable way and ensures that your code will run on any operating system and server setup.

<?php //code... ?>

Documentation

Documenting your code is also important. When all is said and done you want to be able to look back at your code and immediately know what the purpose of a particular Class or function is. Here is an example:

/**
 * Short description of what the class does
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <author@example.com>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: @package_version@
 */
class Foo_Bar_Baz
{
    /**
     * The status of foo's universe
     *
     * @var string
     */
    public $foo = 'unknown';

    /**
     * Short description of what function does
     *
     * @param string $arg1  the string to quote
     * @param int    $arg2  an integer of how many problems happened.
     * @return int  the integer of the set mode used. FALSE if foo
     *               foo could not be set.
     */
    public function fooBar($arg1, $arg2='')
    {
        // code...
        return 1;
    }
}

Please note the above is just a small sample of how you can document your code. There are also a number of additional @tags that you can use in your docblocks, however I have just chosen to show a few. You might also have noticed it is very similar to the way you would do documentation in Java.

Now you may be wondering why it is necessary to go through all that, just to document your code. In all honesty, you don’t have to if you don’t want to, but it is considered best practice to do so. Also picture for a moment you’d like to automatically generate sophisticated documentation in a variety of formats. You can use phpDocumentor to automatically create documentation based on the docblocks in your code. One further benefit of following the standard is that some IDE‘s will use the doc tags to infer information about the source and make this available to you as you code.

Conclusion

Again you might think to yourself, “But I prefer to do my control structures this way and name my classes that way, why should I change to the PEAR way?”. This article was not meant to tell you that you have to change and do it the PEAR way. You are free to code any way you please, but rather, the purpose of this article is to let you know that there is a standard that you can follow and that it is well known and accepted more than any other. Also if you are new to PHP by following said standard it can help you to write your PHP code in a good way from an early stage which will benefit you in the long run.

I hope you found this article helpful. Happy coding. Peace and God bless.

References and Further Reading

Discuss This Topic

  1. 1 Chris Huff

    I code very similar to this. Over time, I felt the need to simply be more consistent in the way that I code. As the codes that I wrote became longer and longer, I needed to be consistent in order to go back and even understand what was going on! Thanks for this overview. I’ll definitely be putting some of this into practice.

     
  2. 2 Nathan Smith

    Thanks Yannick. As a front-end guy who dabbles in the server-side, the issue of what constitutes “good” PHP has always made me curious. Not necessarily object-oriented vs. procedural programming, but exactly what you’ve covered here – agreed upon coding conventions.

     
  3. 3 Tobias Bolt

    Thanks for these informations, Yannick. As I just started to code a new project, I am very glad to have a guideline to coding!

     
  4. 4 Nate Klaiber

    Excellent overview of good programming practices. Keeping these things in mind will help you as you work on a development team or have to hand your code over to someone else to work with.

    I wish there were more agreed upon standards (different frameworks seem to handle a few of the above differently).

     
  5. 5 Yannick

    Chris: Trust me I know the feeling.

    Chris, Nathan and Tobias: You’re welcome. I’m happy it was helpful.

    Nate: I definitely agree with you, it’s certainly a good idea to have an agreed set of coding standards that your development team will follow. And even if you are working on a project by yourself, you could also have a section in your documentation or even a small readme about the coding standards you use so that future developers of the project can follow.

     

Comments closed after 2 weeks.