Code Formatting & Indenting
In this lesson we will look at code formatting and indentation conventions in PHP.
Whitespace
Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace allows the developer looking at your code to have an indentation at levels that they prefer and customize in whatever application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus, say, four space characters.
Line Breaks
Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any case, ensure that your text editor is set up to save files with Unix line breaks.
Code Indenting
Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves and indented at the same level as the control statement that “owns” them.
Example: Incorrect
function foo($bar) {// ...}foreach ($arr as $key => $val) {// ...}if ($foo == $bar) {// ...} else {// ...}for ($i = 0; $i < 10; $i++){for ($j = 0; $j < 10; $j++){// ...}}try {// ...}catch() {// ...}
Example: Correct
function foo($bar){// ...}foreach ($arr as $key => $val){// ...}if ($foo == $bar){// ...}else{// ...}for ($i = 0; $i < 10; $i++){for ($j = 0; $j < 10; $j++){// ...}}try{// ...}catch(){// ...}
Short Open Tags
Always use full PHP opening tags, in case a server does not have short_open_tag
enabled.
Example: Incorrect
<? echo $foo; ?><?=$foo?>
Example: Correct
<?php echo $foo; ?>
One Statement Per Line
Never combine statements on one line.
Example: Incorrect
$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
Example: Correct
$foo = 'this';$bar = 'that';$bat = str_replace($foo, $bar, $bag);
$foo = 'this'