Table of Contents

PHP Coding Standards

Naming Conventions

Variables and Function Agrument names

Example:

function doTest($sumCount, $value){
    $sum = 0;
    for ($i = 0; $i < $sumCount; $i++) {
        $sum += $value;
    }
    return $sum;
}

Constants

Example:

  define('A_GLOBAL_CONSTANT', 'Hello world!');

Hash Array Keys

Example:

  echo $valuesArray[2];  // Bad
  echo $valuesArray[THE_SPECIAL_KEY]; // Good
  echo $valuesArray[foo]; // Very Bad
  echo $valuesArray['foo']; // Bad
  echo $valuesArray[THE_FOO_KEY]; // Good

Functions and Method Names

Use the same convention as variable names

Examples:

getData(), serialize(), isReady()

Class Names

Example:

ClassName, AnotherClass, opClassInOurProject

Class Attribute Names

Example:

  private $_privateData; // wrong - do not perpend private or protected methods with underscore (_)
  public $action; // Public member variable. Don't bother using public variables. When you need to define getter and setter - make it protected and use member overloading.
  protected $action; // Private member variable.

No All Upper Case Abbreviations

People seem to have very different intuitions when making names containing abbreviations. It's best to settle on one strategy so the names are absolutely predictable.

Take for example networkABCKey. Notice how the C from ABC and K from key are confused. Some people don't mind this and others just hate it so you'll find different policies in different code so you never know what to call something.

Example:

  class FluidOz             // NOT FluidOZ
  class GetHtmlStatistic       // NOT GetHTMLStatistic

Control Structures

These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated form:

if ((condition1) || (condition2)){
  action1;
} elseif ((condition3) && (condition4)){
  action2;
} else {
  defaultaction;
}

* Example for() structure:

for ($i = 0; $i < 100; $i++) {
  ...
}

* Example foreach() structure:

foreach ($array as $value) {
}
foreach ($array as $key => $value) {
}
foreach ($array as $key=>$value) { // only here you can skip space around =>
}

* Example switch() structure:

switch ($value) {
  case 1:
    echo 1;
    break;
 
  case 'hello':
    echo 'hello';
    break;
 
  default:
    echo 'default';
}

* Example while() structure:

while ($i < 100) {
  ...
  $i++;
}

* Example do while() structure:

do {
    ...
    $i++;
} while ($i < 100);

Classes

Use the following class declaration style:

class SomeClass extends ParentClass {
  ...
}

Method and Field Modifiers

The method of field modifiers are one or more of:

public protected private abstract static final

Although the order of the modifiers is not significant to the compiler for consistency reasons use the order above, eg:

public static function a()
protected final function b()
public abstract static function a()

Functions

Function Declarations

Functions should be placed inside classes when possible. The syntax of function declarations are showed in the snipped below.

function myFunction($paramA = 1, $paramB = 2){

return 42;

}

Function Calls

Functions shall be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:

$var = foo($bar, $baz, $quux);

As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable.

In the case of a block of related assignments, do not align on the equal sign.

$short         = foo($bar); // WRONG !
$long_variable = foo($baz);

Operators

// assignment operators:
$a = 5;
$my_str .= "bla bla bla";
$i += 2;
 
// logical and comparison operators:
if ($name == 'Victor' or $name == 'Andrei') {
  echo 'Record found!';
}
 
// arithmetic operators:
$a = (10 * $b) / 20;
 
// unary operators:
$i++;
/* what's the result? who knows? */
$bool = ($i < 7 && $j > 8 || $k == 4);
 
/* now you can be certain what I'm doing here. */
$bool = (($i < 7) && (($j > 8) || ($k == 4)))

Parenthesis, brackets and comma

Strings

Indenting

Line Formatting

$result = createUser($username, $password, $password2, $firstName, $lastName,
                     $email, $phone);
$longText = 'This is a very long sentence that ' .
            'needs splitting';

Statements per line

// Correct
$a = 1;
$b = 1;
// Incorrect
$a = 1; $b = 1;

PHP Code Tags

* Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. * Do not put ?> at the end of file when it's not a template. Not closing php tag is allowed and prevents white space at end. Some browsers add a new line at the end of file.

Comments

/*! A comment block it doesn't contain vertical asterisks */

Incorrect:

//some comment

Correct:

// some comment

HTML

Including files

Naming files

SQL Queries

Example:

  $db->query('SELECT * FROM users WHERE id = '.intval($userId).' and status != "'.$db->escape(US_ACTIVE).'"');

Project Structure

FIXME

Example:

/include/
/include/miphpf/
/include/miphpf/const/
/include/miphpf/model/
/include/miphpf/view/
/include/miphpf/util/

Example:

/admin/
/admin/employees/
/admin/managers/
/admin/config/
/admin/lists/

Epilogue

Please follow the standards above. Consider these reasons:

If you find that you are wondering how to write a certain piece of code, and the correct style is not described here, or is not clear, please contact the author/maintainer so that the needed amendment can be made.

And the final point is that the standard is not written in stone. If in a certain situation it makes all the sense in the world not to follow the standard, then do what is best for the project.