PHP Coding Standards

If you’re part of a larger team developing (and sharing) code, it is a pretty good idea to have some common standards. In the PHP work, such a set of common standards include the PEAR Coding Standards. While it may be a challenge to agree on standards, it can be done - the hard part is following the standards.

One excellent tool to help you check for standards compliance is the PHP CodeSniffer. We’ve had it running for quite awhile and it seems to work as advertised. We’ve made our own (“TDC”) coding standards which is a variation over the PEAR coding standards, and checking if you follow them is as simple as running a simple command line. While it doesn’t enforce following of the coding standards, it does make it a no-brainer to check if you do follow the common standards.

The output from the codesniffer could look something like this:

mahler@mahler$ phpcs --standard=TDC Example.php

FILE: Example.php
--------------------------------------------------------------------------------
FOUND 44 ERROR(S) AND 2 WARNING(S) AFFECTING 38 LINE(S)
--------------------------------------------------------------------------------
[LINE 2] ERROR: "require_once" is a statement, not a function. No parentheses are required.
[LINE 5] ERROR: "require_once" is a statement, not a function. No parentheses are required.
[LINE 7] ERROR: Space before opening parenthesis of function call prohibited
[LINE 9] ERROR: Space before opening parenthesis of function call prohibited
[LINE 20] ERROR: Line indented incorrectly. Expected 0 tabs but found 1.
[LINE 49] ERROR: Line indented incorrectly. Expected 1 tabs but found 2.
[LINE 51] WARNING: Equals sign not aligned correctly. Expected 1 space, but found 2 spaces.
[LINE 59] ERROR: Space after opening parenthesis of function call prohibited
[LINE 61] ERROR: Line indented incorrectly. Expected 2 tabs but found 3.
[LINE 61] ERROR: Expected "while (...) {\n" found "while(...){\n".
[LINE 63] WARNING: Equals sign not aligned with surrounding assignments. Expected 3 spaces, but found 1 space.
[LINE 74] ERROR: Line indented incorrectly. Expected 1 tabs but found 2.
...