Style Guide

These conventions are tailored for using PHP as a templating language. They extend the PHP Framework Interop Group’s coding standards: PSR-1 and PSR-2.

PHP code demarcation

Open PHP tags using the full tag (not the shortcut).

<!-- Good -->
<?php $i++; ?>

<!-- Bad -->
<? $i++; ?>

Always end statements with a semi-colon.

<!-- Good -->
<?php $i++; ?>

<!-- Bad -->
<?php $i++ ?>

Always put a space between semi-colons and closing PHP tags.

<!-- Good -->
<?php $i++; ?>

<!-- Bad -->
<?php $i++;?>

Indentation

Use 4 spaces (not tabs) for indentation.

if ($x) {
••••$y = 1;
}

Start writing at the same indentation level as PHP tags.

<!-- Good -->
<?php
$x = 0;
$y = 1;
?>

<!-- Bad -->
<?php
    $x = 0;
    $y = 1;
?>

Strings

String literals

Use single-quotes for string literals.

// Good
$x = 'John Smith';

// Bad
$x = "John Smith";

Use double-quotes for string literals containing single-quotes. This is more readable than escaping characters.

// Good
$x = "John Smith's Account";

// Better: use proper apostrophe characters
$x = 'John Smith’s Account';

// Bad
$x = 'John Smith\'s Account';

String concatenation

Add spaces before/after the concatenation operator for readability.

// Good
$fullName = $firstName . ' ' . $lastName;

// Bad
$fullName = $firstName.' '.$lastName;

Variable substitution

Use concatenation (not variable substitution). Concatenation is less concise, but more intentional and clearer.

// Good
$cartLabel = 'Cart: ' . $cartCount . ' items';

// Bad
$cartLabel = "Cart: $cartCount items";
$cartLabel = "Cart: {$cartCount} items";

Operators

Add spaces around operators for readability.

// Good
$x = 0;
$x = 2 + 1
$x = (2 > 1) ? 1 : 0;

// Bad
$x=0;
$x=2+1;
$x=(2>1)?1:0;

Conditionals

Add spaces around parentheses for readability.

// Good
if ($x === 0) {
    $y = 0;
}

// Bad
if($x === 0){
    $y = 0;
}

Use curly-braces (even for single-line conditionals). This makes intent clearer.

// Good
if ($x === 0) {
    $y = 0;
}

// Bad
if ($x === 0) $y = 0;

// Bad
if ($x === 0)
    $y = 0;