PHP Coding Guidelines

These are the guidelines that I follow when writing my PHP scripts, unless a coding standard
already exists for the project I’m working on. It can be helpful to have something like this if we’re
working on a joint project. You can view the complete article at the URL below

http://www.phpdeveloper.org.uk/articles/php-coding-guidelines/

Editor settings

Tabs v. spaces

Spaces are better as you can guarantee that they will look the same regardless of editor settings. The other benefit to using two spaces is that code doesn’t start to scroll off the right side of the screen after a few levels of indentation.

Linefeeds

The three major operating systems (Unix, Windows and Mac OS) use different ways to represent the end of a line. Unix systems use the newline character (n), Mac systems use a carriage return (r), and Windows systems use a carriage return followed by a line feed (rn). If you’ve ever opened a file created in Windows on a Unix system, you will probably have seen lots of odd characters (possibly represented by ^M) where you would expect to see a clean line break.

If you develop on Windows (and many people do), either set up your editor to save files in Unix
format or run a utility that converts between the two file formats.

Naming conventions

Variable names

Variable names should be all lowercase, with words separated by underscores. For example, $current_user is correct, but $currentuser, $currentUser and $CurrentUser are not.

Names should be descriptive, but also concise. Wherever possible, keep variable names to under 15 characters, although be prepared to sacrifice a few extra characters to improve clarity.

Constants should follow the same conventions as variables, except use all uppercase to distinguish them from variables. So USER_ACTIVE_LEVEL is correct, but USERACTIVELEVEL or user_active_level would be incorrect.

Loop indices

This is the only occassion where short variable names (as small as one character in length) are permitted, and indeed encouraged. Unless you already have a specific counting variable, use $i as the variable for the outermost loop, then go onto $j for the next most outermost loop etc. However, do not use the variable $l (lowercase ‘L’) in any of your code as it looks too much like the number ‘one’.

Function names

Function names should follow the same guidelines as variable names, although they should include a verb somewhere if at all possible. Examples include get_user_data() and validate_form_data(). Basically, make it as obvious as possible what the function does from its name, whilst remaining reasonably concise.

Function arguments should be separated by spaces, both when the function is defined and when it is
called. However, there should not be any spaces between the arguments and the opening/closing
brackets.

Code layout

Including braces

Braces should always be included when writing code using if, for, while etc. blocks. There are no exceptions to this rule, even if the braces could be omitted. Leaving out braces makes code harder to maintain in the future and can also cause bugs that are very difficult to track down.

Some examples of correct/incorrect ways to write code blocks using braces:

/* These are all incorrect */

if ( condition ) foo();

if ( condition )
  foo();

while ( condition )
  foo();

for ( $i = 0; $i < 10; $i++ )
  foo($i);

/* These are all correct */

if ( condition )
{
  foo();
}

while ( condition )
{
  foo();
}

for ( $i = 0; $i < 10; $i++ )
{
  foo($i);
}

Braces should always be placed on a line on their own; again there are no exceptions to this rule.
Braces should also align properly (use two spaces to achieve this) so a closing brace is always in the same column as the corresponding opening brace. For example:


if ( condition )
{
  while ( condition )
  {
    foo();
  }
}

Spaces between tokens

There should always be one space on either side of a token in expressions, statements etc. The only exceptions are commas (which should have one space after, but none before), semi-colons (which should not have spaces on either side if they are at the end of a line, and one space after otherwise).

Control statements such as if, for, while etc. should have one space on either side of the opening bracket, and one space before the closing bracket. However, individual conditions inside these brackets (e.g. ($i < 9) || ($i > 16)) should not have spaces between their conditions and their opening/closing brackets.

In these examples, each pair shows the incorrect way followed by the correct way:


$i=0;
$i = 0;

if(( $i<2 )||( $i>5 ))
if ( ($i < 2) || ($i > 5) )

foo ( $a,$b,$c )
foo($a, $b, $c)

$i=($j<5)?$j:5
$i = ($j < 5) ? $j : 5

Operator precedence

Always use brackets to make it absolutely clear what you are doing.


$i = $j < 5 || $k > 6 && $m == 9 || $n != 10 ? 1 : 2; // What *is* going on here?!?
$i = ( (($j < 5) || $k > 6)) && (($m == 9) || ($n != 10)) ) ? 1 : 2; // Much clearer

SQL code layout

When writing SQL queries, capitialise all SQL keywords (SELECT, FROM, VALUES, AS etc.) and leave everything else in the relevant case. If you are using WHERE clauses to return data corresponding to a set of conditions, enclose those conditions in brackets in the same way you would for PHP if blocks, e.g. SELECT * FROM users WHERE ( (registered = 'y') AND ((user_level = 'administrator') OR (user_level = 'moderator')) ).

General guidelines

Quoting strings

Strings in PHP can either be quoted with single quotes ('') or double quotes (""). The difference between the two is that the parser will use variable-interpolation in double-quoted strings, but not with single-quoted strings. So if your string contains no variables, use single quotes and save the parser the trouble of attempting to interpolate the string for variables, like so:

$str = "Avoid this - it just makes more work for the parser.";
$str = 'This is much better.'

Likewise, if you are passing a variable to a function, there is no need to use double quotes:

foo("$bar"); // No need to use double quotes
foo($bar); // Much better

Finally, when using associative arrays, you should include the key within single quotes to prevent any ambiguities, especially with constants:

$foo = bar[example]; // Wrong: what happens if 'example' is defined as a constant elsewhere?
$foo = bar['example']; // Correct: no ambiguity as to the name of the key

However, if you are accessing an array with a key that is stored in a variable, you can simply use:

$foo = bar[$example];

Shortcut operators

The shortcut operators ++ and -- should always be used on a line of their own, with the exception of for loops. Failure to do this can cause obscure bugs that are incredibly difficult to track down. For example:

$foo[$i++] = $j; // Wrong: relies on $i being incremented after the expression is evaluated
$foo[--$j] = $i; // Wrong: relies on $j being decremented before the expression is evaluated

$foo[$i] = $j;
$i++; // Correct: obvious when $i is incremented

$j--;
$foo[$j] = $i; // Correct: obvious when $j is decremented

Optional shortcut constructs

As well as the useful increment and decrement shortcuts, there are two other ways in which you can make your PHP code easier to use. The first is to replace if statements where you are assigning one of two values to a variable based on a conditional. You may be tempted to write something like this:

if ( isset($_POST['username']) )
{
  $username = $_POST['username'];
}
else
{
  $username = '';
}

if ( isset($_POST['password']) )
{
  $password = md5($_POST['password']);
}
else
{
  $password = '';
}

Whilst the above code works and makes it obvious what you are doing, it’s not the easiest or clearest way if you want to run through a list of different variables and do a similar thing to all of them. A more compact way would be to use the ternary operator ? : like so:

$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? md5($_POST['password']) : '';

Use constants where possible

If a value is not going to change throughout the execution of your script, then use a constant rather than a variable to define it. That way, if you do change the value by accident, the PHP parser will output an error and allow you to fix the problem, without it causing any unforeseen side effects.

Remember that constants should never be enclosed in strings, either single or double. You must always use concatenation if you wish to include a constant’s value in a string.

Turn on all error reporting

A lot of code I’ve downloaded from the web and tried to use has failed on my machines because the developers switched off the E_NOTICE flag in their PHP configuration for some reason or another. As soon as I bring it onto my system, where error reporting is set to E_ALL (i.e. show all errors, including references to variables being used without being initialised), the PHP interpreter spews out dozens of error messages which I then have to fix before I can proceed to use the script.

What you need to remember as a developer is that the person who uses your script may not have exactly the same php.ini configuration as you so you aim for the lowest common denominator, i.e. all error reporting enabled. If your code works with E_ALL set, then it will also work with any other error reporting configuration, including when all error reporting is turned off (e.g. on sites where PHP errors are logged to a file instead).

If you write proper object oreintated code and make sure that each class doesn’t produce any errors, you should be able to make your program as a whole run without errors under normal circumstances.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x