JavaScript, jQuery, HTML5, CSS & More

Archives

Meta

PHP Coding Guidelines

The following PHP coding guidelines represent my own conventions and standards which I code by, along with some CakePHP conventions when developing with CakePHP, my PHP MVC framework of choice.

These PHP coding guidelines are by no means an industry standard, nor are they intended to tell you PHP coders out there how things should be done. I simply want to share the PHP coding guidelines which I follow and enforce when working with other developers on larger projects.

Laying down some coding guidelines like these helps to provide a more structured and rapid development environment, and makes the PHP code more predictable and easier to debug.

PHP Code Delimitation

PHP code must always be delimited by the full-form, standard PHP tags:

Always use four spaces for code indentation. Do not use actual tabs. This prevents spacing issues when opening documents in different types of editors and when viewing source code in browsers. Most editors (e.g. Eclipse, Dreamweaver) allow you to set the tab key to insert a defined number of spaces instead of an actual tab. Setting this preference in your editor is strongly encouraged so as to speed up development and to prevent tabs from accidentally being inserted.

Note: To configure this in Eclipse PDT, go to Window -> Preferences -> PHP -> Formatter and set “Tab Policy” to “Spaces” and “Indentation size” to “4”.

String literals

When a string is literal (contains no variable substitutions), the apostrophe or single quote must always be used to demarcate the string, unless that string itself contains apostrophes. PHP will parse all double-quoted strings for occurences of variable substitution, thus taking more time to process. For enterprise-level applications with the possibility of hundreds of concurrent users, this can amount to a significant reduction in performance.

Standard string literals

$sVar='A string';

$sVar = 'A string';

This rule goes for strings within function calls and constructs as well:

fooBar('string1','string2');print'This is a string';

fooBar('string1', 'string2');
print 'This is a string';

Note: Using double quotes for string demarcation throughout programs can increase processing time significantly, thus they are not permitted unless the string itself contains apostrophes.

String literals containing apostrophes

When a literal string itself contains apostrophes, it is permitted and preferred to demarcate the string with quotation marks or “double quotes.” This is especially encouraged for SQL statements:

$sql="SELECT id, name FROM people WHERE name = 'Fred' OR name = 'Susan'";

$sql = "SELECT id, name FROM people WHERE name = 'Fred' OR name = 'Susan'";

Note: The above syntax is preferred over escaping apostrophes so as to improve readability. Double quotes are only permitted when the string itself contains apostrophes.

Inline concatenation

Multiple line concatenation

When concatenating strings with the “.” operator, it is permitted to break the statement into multiple lines to improve readability. In these cases, each successive line should be indented with at least four spaces (1 tab), and the same number of spaces must be used for each indented line such that the “.” operators are aligned on the left side.

$sql='SELECT id, name FROM people '."WHERE name = 'Susan' ".'ORDER BY name ASC';

$sql = 'SELECT id, name FROM people '
. "WHERE name = 'Susan' "
. 'ORDER BY name ASC';

You may also concatenate a string by redefining it with the concatenation operator (when necessary):

$sql='SELECT id, name FROM people ';$sql.="WHERE name = 'Susan' ";$sql.='ORDER BY name ASC';

An alternative to concatenating ouput is using the echo() construct with multiple parameters, separated by commas:

echo'Concatenate this string with ',$var1,' and ',$var2,'.';

echo 'Concatenate this string with ', $var1, ' and ', $var2, '.';

Although the concatenation operator ( . ) may be used with the echo() construct, the above syntax should be used instead for optimal performance. Using the concatenation operator with the echo() construct stores each concatenated section of the string as a separate object in memory before printing to the screen. Therefore, concatenating with the echo() construct is not permitted.

print() vs. echo()

You can find much discussion regarding this on the web. echo() is shown to have a marginal but insignificant advantage in speed over print() when used in simple, non-concatenated instances. This difference is not enough to be a concern, however.

For sake of consistency, it is preferred that developers use print() in all cases. The print() construct also provides a few advantages over echo() which are favorable from a programming point of view:

Although it is a construct and not a function, print() will return a value of 1 (true), whereas echo() has no return value.

Concatenating strings with the print() construct does not require additional stores to memory before executing.

// Because echo() does not behave like a function, the following code is invalid.returnecho'true';// However, the following example will work:returnprint'true';

// Because echo() does not behave like a function, the following code is invalid.
return echo 'true';
// However, the following example will work:
return print 'true';

Class declaration

Classes must be named by following the CakePHP naming conventions, and must use CamelCase notation. There should always be a single space between the class name and the opening bracket, and the opening bracket must be on the same line as the class name. The closing bracket must be on its own line at the end of the class declaration.

class MyFlippinSweetClass {}

class MyFlippinSweetClass {
}

Class member variables

Any variables declared in a class must be listed at the top of the class, prior to declaring any functions.

PHP 5+ only: The var construct is not permitted. Always declare the visibility of member variables by using one of the private, protected, or public constructs. Accessing member variables directly by making them public is permitted but discouraged in favor of accessor methods (typically prefixed with “set” or “get”).

All protected member variable names should begin with a single underscore (“_”), and all private member variable names should begin with two underscores (“__”). This is the only acceptable usage of underscores in a variable names. Member variables declared “public” may never start with an underscore.

Class member functions

If using PHP 5+, we have the advantage of using the public, protected, and private constructs for declaring functions. For sake of convention and compliance with CakePHP, however; all protected member function names should begin with a single underscore (“_”), and all private member function names should begin with two underscores (“__”). This is the only acceptable usage of an underscore in a function name. Public member functions may never start with an underscore.

Additionally, The return value must not be enclosed in parentheses. This can hinder readability and can also break code if a method is later changed to return by reference.

Class instantiation

Note: Only variables representing objects may begin with a capital letter (as do class names). This helps to differentiate these declarations from other variable types.

Function declaration

Function names should be written using camelBack notation. There is no space between the function name and the opening parenthesis for the arguments. Like classes, there should always be a single space between the function name and the opening bracket, and the opening bracket must be on the same line as the function name. The closing bracket must be on its own line at the end of the function declaration.

function myFlippinSweetFunction(){}

function myFlippinSweetFunction() {
}

Additionally, functions should always be declared within a class, and should never stand alone. This provides a namespace for all functions and helps to identify their classification and location. For example, we would like to create a set of common functions that may be used throughout our application.

Variable declaration

Variable names should always begin with a lowercase key letter defining the data type, except for variables representing objects which begin with a capital letter. Object variables representing classes are the only variables that may begin with a capital letter, and they must match the class name. All variable names should be written in camelBack notation (or CamelCase for object variable names).

Key letters

The following key letters must be used to define variable data types:

i = integer;

f = float;

s = string;

b = boolean;

a = array;

r = resource id / reference;

m = mixed.

Note: “Mixed” refers to any variable that may change data types during a request, such as inside a foreach loop.

Variable names should also be descriptive, but as short as possible. Single character variable names are not permitted, except when used for incrementing / decrementing inside for and while loops. For example:

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

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

NOTE: The rules for defining variable names apply to naming associative array keys as well. An exception to this rule for associative array keys is when you intend to use the key names for literal output to the user agent.

Control statements

All control statements must have a single space before the opening parenthesis of the conditional, and a single space after the closing parenthesis.

If / else / elseif statements

For “if” statements that include “elseif” or “else”, the formatting must be as in these examples:

Switch statements

Each “case” within the “switch” statement must be indented 4 spaces (1 tab). Content under each “case” statement must be indented an additional 4 spaces. The “default” construct may never be omitted from a switch statement. The “break” for each case should always align with its respective “case” declaration.

NOTE: It is sometimes useful to write a case statement which falls through to the next case by not including a break or return in that case. To distinguish these cases from bugs, any case statement where break or return are omitted must contain the comment “// break intentionally omitted”.

Ternary operator

The ternary operator (?:) is permitted only when assigning values to variables, printing output, or returning values. It may not be used in place of if / else statements which define program logic. To enhance readability, always place parentheses around the conditional statement.

Including files

When including files that are used only once in a single request (e.g. classes, libraries, configuration), use only and always the require_once() function. This prevents the accidental inclusion of a file more than once. Only use the require() (not include()) function for files that may be used more than once in the same request.

The above example illustrates requiring classes just once which then lend themselves to reuse by instantiating multiple objects, whereas the require() statement implies that the program output is consumable HTML.

require() vs. include()

The require() and require_once() functions are always preferred over the include() and include_once() functions. require() and require_once() will generate a fatal error and prevent the script from continuing to run if the specified file is not found, which in most cases would be a desirable outcome since the rest of the script will likely not run correctly without that file. include() and include_once() will only generate a warning if the file is missing and PHP will attempt to run the remainder of the script. require() and require_once() should be used in all cases so that it is always evident when an included file is missing (ideally during development), even if warnings are suppressed.

Constants

Constants should be defined in capital letters with words separated by an underscore “_”. Each constant should begin with an appropriate namespace to help derive its meaning:

While you should try and keep constant names short, always ensure that the names are unique enough to prevent collisions with other constants defined in any third party plugins.

Documentation formatting / comments

All documentation blocks (“docblocks”) must be compatible with the phpDocumentor format.

All source code files written for the framework or that operate within the framework must contain a “file-level” docblock at the top of each file and a “class-level” docblock immediately above each class. Below are examples of such docblocks.

Note: The $ SVN keywords will be automatically updated by Subversion when the svn:keywords property is added to the file. Whenever creating a new PHP file to add to the Subversion repository, be sure to add the property like so: