PHP Coding Style

I've been looking to make my code as readable as possible and being consistent when I write code, so that all my code looks the same.  This allows other developers and myself, when trying to read old code months later, to have an easier time figuring out what a particular piece of code does and how it does it.  It also gives me a certain amount of pride to write neat, well documented code.

Once you start the process of defining your style, you want to incorporate ideas from other developers.  One of the clearest coding style documents I've seen was written for the Kohana PHP framework documentation.  Part of their documentation was an article entitled, Conventions and Coding Style, that the Kohana developers recommended for writing code.

Documenting and commenting your code is important to make your code understandable and readable.  The PHP standard for doing that is to use  PHPDoc.  PHPDoc will compile documentation of your code for you if you follow their specific styling while writing your code.  PHPDoc has a PHPDocumenter Guide that tells you how to do that.

I've found both of these styles combined make for excellent coding style, and I highly recommend both.  Below is an abbreviated synopsis of their two coding styles that you can use as a reference for your own code.

CLASSES
One class per file

CODE SPACING
Use tabs set at 4 spaces to indent code, do not use spaces.
Use spaces only to vertically align multi-line text passages.
Lines are 80 characters wide before going "off" page and need wrapping.
Try to stay within 80 character lines for readability

COMMENTS - SINGLE LINE and INLINE
One space after the inline symbol, "// "
The first letter is capitalized.
Example:  // The comment

CONCATENATION
$strtom = 'one'.$strvar.'two';
No spaces around concatenation

CONDITIONALS

if ($tom == $ed)
{
    if ($strfoo == 'bar')
    {
       $baz->bar();
    }
    elseif ($tom == $Jerry)
    {
       $baz->default();
    }
}

Brackets are on their own line
Indent one tab at each level

THE DOCUMENTATION BLOCK
/**
* Top line - one line summary of class or method
*
* Detailed description of how the method
* does what it does
*
* @category name        // A way to group packages
* @package  name        // A way to group related elements
* @subpackage name    // Way to sub group packages
* @param int $tom        // A param passed into the method
* @return int $tom    // What is returned
* @see subclass::foo    // One way link to this method
* @see parent_method()// Another example of @see
* @uses filename        // Creates a two way link back
* @static                // Used on static methods
* @todo                // Bookmark to work not done
* @tutorial            // Link to reference documentation
* @var string            // Doc a variable in the method
*
*/
static function dog {}    // On the next line after doc close
To connect the class or method to the documentation, the class or method has to start on the next line after the closing documentation tag.

PARENTHESES
if ($foo == $bar)
One space after the statement tag

if ($foo == $bar)
No spaces after open or before the closing parenthesis

if ( ! $foo)
The bang character has space on each side for readability

TYPE CASTS PARENTHESIS
$strfoo = (string) $bar;
if ( (string) $bar)
Type casts should have spaces on each side

PHP CLOSING TAG "?>"
The PHP closing tag "?>" should not be at the end of a file
It is not needed, and this prevents a space after the end of file ?> causing an error that is hard to find.
The closing tag is needed if it is not the last code on the page

REGULAR EXPRESSIONS
Only use PERL reqular expressions, not POSIX
if (preg_match('/abc/i'), $str)
Use single quotes around expression

preg_match('/abc/', $str);
Use single quotes around expression

preg_replace('/(\d+) dollar/', '$1 euro', $str);
Use $n for replace

SWITCH

switch ($rob)
{
    case 'foo':
        echo 'hello';
        break;
    case 1:
        echo 'one';
        break;
    default: 
        echo 'bye';
        break;
}

TERNARIES
$foo = ($bar == $foo) ? $foo : $bar;
$foo = $bar ? $foo : $bar;

$foo = $bar ?: $tom
PHP5.3 and higher
If $bar is true $foo = $bar, if false $foo = $tom

If you prefer other code styling that is fine, to each his own, this is just one way.  The important thing to take away from this post is to be consistent by using the same styling guide to all your code.  Once you get in the habit of writing code one way, it makes coding move a lot faster and as a result your code becomes more readable.

Comments are closed.