PHP Coding Guidelines

Naming convensions and best coding practices for industry standard development using PHP. The objective is to produce high quality and consistent coding style throughout projects, increase productivity by increase code readability (and understandability). These guidelines are used by my fellowers and I, and obeyed as our coding standards.

These guidelines are for generic PHP4/5 coding and should fit nicely with convensions by different PHP frameworks.

What’s Not Covered in this Guide

  • Coding practise using PHP
  • Comment semantic and style (will be in another document)

Changelog

10/02/2010: First publish.

Rules of Thumb

  1. No camelCase and minimise appearance of upper case.
  2. No short hands, no abbreviation and common known acronyms are acceptable.

Code Formatting

Brackets

Use Allman style bracketing.

Comments

Use // for commenting out code.

Use //– for adding inline notes.

Indentation

Use 4 spaces per indent instead of a tab or 2 spaces. Most IDEs allows to be configured to output spaces when hit Tab key on keyboard.

Naming Convensions

Use under score naming and not camel case nor pascal case.

This applies to variable name, method name, class name.

Constants

Use all upper case with under score naming with prefix.

eg/ MY_ENABLE_CACHE = 0;

Variable Datatype

Although PHP allows dynamic type for variables, you should stick a variable to an dedicated datatype.

Type Casting

Refer to Type Juggling in PHP Manual for correct usage of type casting.

Perference

It is important to adopt one common agreed convension within the team for better readability between peers.

Single Line Statements

New line, indent and without bracket.

Do not place 2 line of code in one line.

Equal sign alignment

If it helps increase readability, you are recommended to align your equal signs.

Comparison Operations

Use OR and AND keyword instead of || and &&

Else if statement

Use elseif, not else if.

Switch statement

Do not place logic, statements or calculations for more than 1 lines within each case. To simplify, only have 1 line of code per case, use function or if statement for others.