Skip to content
zenmiu edited this page Aug 4, 2011 · 3 revisions

Opening and closing PHP tag

Required:

  1. For files containing PHP code only, the closing tag ("?>") is not entered [REQ.PHP.2.1.1].
  2. The opening tag must be complete [REQ.PHP.2.1.2].

Maximum line length

Required:

Line length cannot exceed 120 characters, except: [REQ.PHP.2.2.1].

  1. Declarations of class properties.
  2. Individual test lines.
  3. Test blocks (so-called heredoc and nowdoc).
  4. In class declarations if the implements block is placed on a new line and still exceeds the length restriction.

Examples of exclusions:

class A {
    protected $z = ‘111....150 symbols...111’;
}

$a = ‘111....150 symbols...111’;

func(
    ‘111....150 symbols...111’
);

$a = array(
    ‘111....150 symbols...111’,
);

$a = <<<DOC
111....150 symbols...111
DOC;

New lines

Required:

  1. New line character - line feed character (LF or \n or 10 or 0x0a) [REQ.PHP.2.3.1].
  2. In all the cases when the text with the new line is not expected to go beyond the current server, use the PHP_EOL constant for the line feed character.
  3. In the cases when the text with the new line is expected to be transferred to other computer, use the Windows-based line feed character (\n\r or 10+13 or 0x0a + 0x0d).

##Indents/tabs/spaces

Required:

Indent for each new level - 4 spaces [REQ.PHP.2.4.1].

Recommendations:

Place as many indents as necessary but not more than you actually need. If you are indenting further than the 7th level, think about taking the code into a separate block [WRN.PHP.2.4.1].

Justification:

  • When people use different tab values, the code often appears unreadable and unprintable; therefore, spaces are more preferrable.
  • Nobody will ever come to an agreement on the most suitable number of spaces. Just be consistent. 4 spaces are the most common.
  • The majority of PHP applications use 4 spaces.
  • The majority of text editors use 4 spaces.

Example:

function func() {
    if (something bad) {
        if (another thing bad) {
            while (more input) {
            }
        }
    }
}

Control structures

Required:

  1. In control structures, there must be a space between the key word and the opening bracket [REQ.PHP.2.5.1].
  2. The opening bracket is to be placed on the same line with the respective operator [REQ.PHP.2.5.2].
  3. The closing bracket is to be placed on the same indent with the operator [REQ.PHP.2.5.3].
  4. The closing curly bracket is to be placed on the next (following the conventional code) line [REQ.PHP.2.5.4].
  5. The entire content between the brackets is to be indented [REQ.PHP.2.5.5].
  6. The code in the body is always framed by curly brackets [REQ.PHP.2.5.6].
  7. Values cannot be assigned to variables within control structures, except within for [REQ.PHP.2.5.7].
  8. If a code block within curly brackets is large (a body is large when it has 4 or more lines of code or 1 line of comments to the body), it must be preceded by a blank line [REQ.PHP.2.5.10] [!].

Extension for operator if/else/elseif

Required:

  1. The elseif operator is placed on a single line [REQ.PHP.2.5.8].
  2. A block of code within curly brackets is to be followed by a blank line if it is followed by else or elseif [REQ.PHP.2.5.9] [!].
  3. Use elseif instead of the else if combination [REQ.PHP.2.5.11].

Example:

if ((condition1) || (condition2)) {
    action1;
} elseif ((condition3) && (condition4)) {
    bigaction2;
} else {
    defaultbigaction;
}

Extension for operator Switch

Required:

  1. The case block, passing the control further down, must have a comment [REQ.PHP.2.5.12].
  2. The default block is always present [REQ.PHP.2.5.13].
  3. Each case block must be followed by a blank line, separating the block from a neighbor [REQ.PHP.2.5.14].
  4. The content of each case expression must be indented [REQ.PHP.2.5.15].
  5. One blank line must be placed between switch, before the first case expression.

Example:

switch (...) {
    case 1:
        // break intentionally omitted
    case 2: {
        $v = get_week_number();
        ...
        }
        break;
    default:
        ...
}

Extension for ternary conditional operator ? :

Recommended:

  1. Enclose the condition expression in brackets, thus distinguishing it from the rest of the code [WRN.PHP.2.5.1].
  2. Where possible, the actions to be performed on the condition should be simple functions.
  3. If the entire branch block, located on a single line, is difficult to read, place the variant1 and variant2 blocks on a separate line each.

Example:

(condition) ? funct1() : func2();

or

(condition)
    ? long statement
    : another long statement;

Extension for operators for, do .. while and while

Recommended:

Minimize the use of continue and break [WRN.PHP.2.5.4].

Rules for placing brackets () in operators and functions

Required:

  1. Always enclose operator parameters in brackets, even when those can be omitted (e.g., echo), except return and the include/require family of operators [REQ.PHP.2.6.1].
  2. The expression in brackets may be broken into multiple lines provided the following:
  • The closing bracket is aligned to the operator [REQ.PHP.2.6.2].
  • Only top-level expressions are carried over.
  • The first expression begins with a new line [REQ.PHP.2.6.4].
  • Expressions following the first one are carried over with the logical operators[REQ.PHP.2.6.5].
  • Expressions have the next level of indentation [REQ.PHP.2.6.6].
  • The closing bracket begins on a new line [REQ.PHP.2.6.7].
  1. Operator and the opening bracket are separated with a space [REQ.PHP.2.6.8].

Example:

if (condition) {
}
while (condition) {
}
if (
    condition1
    && condition2
    && condition3
) {
}
strcmp($s, $s1);
return 1;

Using functions and methods

Required:

  1. Passing by reference during a call is not allowed [REQ.PHP.2.7.1].
  2. Calling a function through a variable with its name must be commented out [REQ.PHP.2.7.2].
  3. The name of the function being called must be followed by the opening bracket without spaces [REQ.PHP.2.7.3].
  4. No spaces must be placed between the closing bracket and the semicolon character if the function call is not involved in the expression [REQ.PHP.2.7.4].
  5. Separate function arguments with a comma, with no space before a comma [REQ.PHP.2.7.5].
  6. Do not place spaces before and after an argument [REQ.PHP.2.7.6].
  7. In multi-line function calls: a. The arguments block must have the next level of indentation [REQ.PHP.2.7.7]. b. The first argument must begin with the new line [REQ.PHP.2.7.8]. c. The closing bracket must be placed on a separate line, aligned to the function name [REQ.PHP.2.7.9].
  8. Assigning values to variables in function calls is not allowed [REQ.PHP.2.7.10].

Recommended:

For functions with arguments that allow arrays, the function call may include the array construction and may be split into multiple lines for better readability. In this case, the array description standard applies.

Example:

threeArguments(array(1, 2, 3), 2, 3);
threeArguments(
    array(
        1, 2, 3, 'Zend', 'Studio',
        $a, $b, $c,
        56.44, $d, 500
    ),
    2,
    3
);

getUserData( $username, $password ); // неправильно
getUserData($username,$password);    // неправильно
getUserData($username, $password);   // правильно

Formatting expressions

Required:

  1. Each complete expression must be separated from the neighbor with a space [REQ.PHP.2.8.1].
  2. The equation sign in a multi-line expression must be on the new line [REQ.PHP.2.8.2].
  3. The right part of an assignment operation along with the equation sign must have the next level of indentation [REQ.PHP.2.8.3].

Example:

$i=0;   // correct
$i = 0; // incorrect

if(( $i<2 )||( $i>5 ))       // incorrect
if ( ($i < 2) || ($i > 5) )  // correct

foo ( $a,$b,$c )  // incorrect
foo($a, $b, $c)   // correct

$i=($j<5)?$j:5          // incorrect
$i = ($j < 5) ? $j : 5  // correct

Recommended:

  1. Each logical expression may be enclosed in brackets depending on the complexity of that expression and the expression it is included in (see Example 1).
  2. In comparison operations, constants must always be on the left (see Example 2) [WRN.PHP.2.8.2].
  3. Use === instead of == where it is possible and improves the security of the code.

Example 1:

$i = $j < 5 || $k > 6 && $m == 9 || $n != 10 ? 1 : 2;                 // incorrect

$i = ( (($j < 5) || $k > 6)) && (($m == 9) || ($n != 10)) ) ? 1 : 2;  // correct but overloaded way

$i = ( ($j < 5 || $k > 6)) && ($m == 9 || $n != 10) ) ? 1 : 2;        // correct light way

Example 2:

if (6 == $errorNum) {
    ...
}

The first reason to do it this way is that the parser will spot an error if you place only one equation sign ('=') instead of two. The second reason – when reading the code you find the value you need right off, at the beginning of the condition, and do not look for it somewhere at the end. It takes time to get used to this format, but this style is really useful.

Strings

Associative array keys are also referred to as strings.

Required:

  1. Enclose strings in single quotes (apostrophes), except the situations when the string consists of only tab characters, end of line or carriage return [REQ.PHP.2.9.1].
  2. Strings are to be joined by the "." operator. Always added a space before and after the "." operator for better readability[REQ.PHP.2.9.3].

Example:

$a = 'Example String';

$greeting = "Hello $name, welcome back!";          // incorrect substitution
$greeting = "Hello {$name}, welcome back!";        // incorrect substitution
$greeting = 'Hello ' . $name . ', welcome back!';  // correct substitution

$company = 'Zend' . 'Technologies';                // correct string concatenation

When concatenating strings with the "." operator, the expression may be broken into multiple lines for better readability. In this case, each next line should be filled with spaces to properly align the opening quotes:

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

Aligning variable declaration blocks

Recommended: A variable declaration block is to be aligned. Variable initialization blocks are also recommended to be aligned.

$mDate  = 0;
$mrDate = NULL;
$mrName = 0;
$mName  = NULL;

Formatting return

Required:

In a function body, add a blank line before return for better readability of the code, except when return is used as the only line in a certain code block [REQ.PHP.2.11.1].

Recommended:

It is recommended to have 1 return in 1 function [WRN.PHP.2.11.1].

function makeCoffee() {
    if (false !== isSleeping() && false !== hasEnoughCafeineForToday()) {
        canMakeCoffee();
        return 1;
    } elseif (nowSleep()) {
        return 2;
    } else {
        cantMakeCoffee();
    }

    return null;
}

Formatting method and/or object variable calls

Required:

  1. When carrying a serial method and/or object variable call over to a new line, carry the call over along with the object operator (the '->' tag) [REQ.PHP.2.12.1].
  2. Object’s operators must be on the next level of indentation [REQ.PHP.2.12.2].

Example:

$object
    ->getById($id)
    ->setName($name);
Clone this wiki locally