Home  >  Article  >  Backend Development  >  PHP Coding Style Guide (PHP-FIG PSR-2)

PHP Coding Style Guide (PHP-FIG PSR-2)

WBOY
WBOYOriginal
2016-08-08 09:28:281433browse

This guide is an extension of the PSR-1 Basic Coding Standard.

This guide lists common PHP code format rules and suggestions, aiming to reduce the cognitive barriers caused by differences in coding styles of different authors.

The style conventions here are derived from several member projects. Guideline authors collaborated on multiple projects to advance these guidance provisions. The key to guidance is sharing, not the rules themselves.

Keywords involved in the article are "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED" Recommended, MAY, and OPTIONAL are described in RFC 2119.

Overview

  1. Code must follow the "Basic Coding Standards" PSR [PSR-1].
  2. Code indentation must use 4 spaces instead of tabs.
  3. There must be no hard limit on line length; the soft limit must be 120 characters; it should be less than or equal to 80 characters.
  4. There must be a blank line after the namespace declaration, and there must also be a blank line after the use declaration.
  5. The { of the class must be on the next line of the class name, and } must be on the next line of the body.
  6. The { of the method must be on the next line of the method signature, and } must be on the next line of the body.
  7. All properties and methods must have visibility set; abstract and final must be declared before visibility; static must be declared after visibility.
  8. There must be a space after the structure control keyword; methods and functions must have no space.
  9. The { of the structure control must be on the same line, and } must be on the next line of the body.
  10. There must be a space after the structure-controlled ( and there must be no space before the structure-controlled ).

Example

The following is a comprehensive example to help you have a general understanding of the rules.

namespaceVendor\Package;

useFooInterface;
useBarClassasBar;
useOtherVendor\OtherPackage\BazClass;

classFooextendsBarimplementsFooInterface
{publicfunctionsampleFunction($a, $b = null)
    {if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }

    finalpublicstaticfunctionbar()
    {// 方法 body
    }
}

Basic Rules

Basic Coding Standards

Code must follow the terms of PSR-1.

Files

  1. All files must use Unix LF (linefeed) line breaks.
  2. All PHP files must end with a single blank line.
  3. Code containing only PHP must ignore the php closing tag ? >.

Line

  1. There must be no hard limit on line length.
  2. The soft limit on length must be 120 characters; automatic code style checking must set 120 characters as a warning and must not be set as an error.
  3. Lines should not exceed 80 characters; lines exceeding this length should be split into multiple lines of no more than 80 characters.
  4. Non-blank lines must end with no trailing spaces.
  5. To enhance readability, blank lines can be added to mark the relevance of the code.
  6. Each line must contain no more than 1 statement.

Indentation

  1. Code must use 4 spaces for indentation, and tabs must not be used as indentation.

Note: Only use spaces, no tabs, to help avoid problems with diffs, patches, history and annotations. Using spaces also helps with alignment.

Keywords (reserved words) and true/false/null

  1. PHP reserved words must be lowercase.
  2. PHP constants true, false and null must be lowercase.

Namespace and Use declarations

  1. namespace declaration must be followed by Blank line.
  2. All use statements must come after the namespace statement.
  3. Each statement must use a separate use.
  4. There must be a blank line after the use declaration area.

For example:

namespaceVendor\Package;

useFooClass;
useBarClassasBar;
useOtherVendor\OtherPackage\BazClass;

// ... additional PHP code ...

Class, attribute and method

"Class" here includes class, interface and trait.

Inheritance and implementation

extends and implements keywords must be declared on the same line as the class name.

class { must occupy one line; } must be on the next line of the body.

namespaceVendor\Package;

useFooClass;
useBarClassasBar;
useOtherVendor\OtherPackage\BazClass;

classClassNameextendsParentClassimplements \ArrayAccess, \Countable
{// constants, properties, methods
}

implements When there are multiple interfaces, the interface list can be divided into multiple lines, and each subline has an indent. If you do this, the first interface must be on the line after implements, and there can be only one interface per line.

namespaceVendor\Package;

useFooClass;
useBarClassasBar;
useOtherVendor\OtherPackage\BazClass;

classClassNameextendsParentClassimplements
    \ArrayAccess,
    \Countable,
    \Serializable
{// constants, properties, methods
}

Properties

All properties must declare visibility.

Var keyword must not be used to declare properties.

Only one attribute must be declared per line.

Protected and private attributes should not be marked with a prefix underscore.

Example:

namespaceVendor\Package;

classClassName
{public$foo = null;
}

Methods

All methods must declare visibility.

Protected and private methods should not be marked with a prefix underscore.

When declaring a method, there must be no space after the method name. { must be on the same line, } must be on the next line of body. (There must be no space after (), and there must be no space before).

An example of a method declaration is as follows. Pay attention to the position of parentheses, commas, spaces and curly braces:

namespaceVendor\Package;

classClassName
{publicfunctionfooBarBaz($arg1, &$arg2, $arg3 = [])
    {// method body
    }
}

Method parameters

In the formal parameter list of the method, there must be no space before each comma. Parameters with default values ​​must be last in the parameter list.

namespaceVendor\Package;

classClassName
{publicfunctionfoo($arg1, &$arg2, $arg3 = [])
    {// method body
    }
}

The parameter list can be divided into multiple lines, and each sub-line must have an indent. If you do this, the first parameter must be on its own line, and there can only be one parameter per line.

When the parameter list is divided into multiple lines, the right bracket ) and the left curly bracket { must be on the same line, and there must be a space before them.

namespaceVendor\Package;

classClassName
{publicfunctionaVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {// method body
    }
}

abstract, final and static

Abstract and final declarations must be declared before visibility.
The static declaration must come after visibility.

namespaceVendor\Package;

abstractclassClassName
{protectedstatic$foo;

    abstractprotectedfunctionzim();finalpublicstaticfunctionbar()
    {// method body
    }
}

Method and function calls

写方法或函数调用时,方法/函数名 和 左括号( 之间,必须没有空格, 右括号 ) 之前必须没有空格。在参数列表中,逗号间必须没有逗号,每个逗号后必须有一个空格。

$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);

控制结构

控制结构通常遵循以下风格:

  1. 控制结构关键词后必须有一个空格。
  2. 左括号后必须没有空格。
  3. 右括号前必须没有空格。
  4. 又括号和左花括号之间必须有一个空格。
  5. body必须有一层缩进。
  6. 右花括号必须在body下一行。
  7. 每个控制结构的body必须用花括号括起来。 即保证外观统一,又减少了添加新行时引入的错误。

if, elseif, else

if 结构如下所示。注意括号、空格、花括号的位置;同时留意 else 和 elseif 与前一部分的 } 在同一行。

if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

elseif关键字不应该被 else if 代替。

switch, case

Switch结构如下所示。注意括号、空格和花括号的位置。 case 语句相对于switch必须有一个缩进, break关键字 或者其他终结性的关键字必须和case body在同一缩进层级。在非空的case body,如果没有终结性语句,必须加上注释 // no break

switch ($expr) {
    case0:
        echo'First case, with a break';
        break;
    case1:
        echo'Second case, which falls through';
        // no breakcase2:
    case3:
    case4:
        echo'Third case, return instead of break';
        return;
    default:
        echo'Default case';
        break;
}

while, do while

while结构如下所示。 注意括号、空格和花括号的位置。

while ($expr) {
    // structure body
}

do-while接口如下所示。 注意括号、空格和花括号的位置。

do {
    // structure body;
} while ($expr);

for

for 结构如下所示。 注意括号、空格和花括号的位置。

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

foreach

foreach 结构如下所示。 注意括号、空格和花括号的位置。

foreach ($iterableas$key => $value) {
    // foreach body
}

try, catch

try-catch区块如下所示。 注意括号、空格和花括号的位置。

try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}

Closure 闭包

声明闭包必须在function关键字后留一个空格,在use关键字前后各留一个空格。

左花括号必须在同一行, 右花括号必须在body的下一行。

参数或变量列表的左括号后 和 右括号前必须没有空格。

参数和变量列表的逗号前必须没有空格,每个逗号后必须有一个空格。

有默认值的参数必须排在最后。

闭包的声明如下所示。 注意括号,逗号,空格和花括号的位置:

$closureWithArgs = function($arg1, $arg2) {// body
};

$closureWithArgsAndVars = function($arg1, $arg2)use($var1, $var2) {// body
};

参数列表和变量列表可以拆分到多行,每个子行有一层缩进。 这么做的时候,第一个列表成员必须独占一行,每行只能有一个列表成员。

参数或变量列表拆分为多行时,到了列表的末尾, 右括号 和 左花括号必须放在同一行,中间有一个空格。

例子:

$longArgs_noVars = function(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
) {// body
};

$noArgs_longVars = function()use(
    $longVar1,
    $longerVar2,
    $muchLongerVar3
) {// body
};

$longArgs_longVars = function(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
)use(
    $longVar1,
    $longerVar2,
    $muchLongerVar3
) {// body
};

$longArgs_shortVars = function(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
)use($var1) {// body
};

$shortArgs_longVars = function($arg)use(
    $longVar1,
    $longerVar2,
    $muchLongerVar3
) {// body
};

注意:当闭包被直接作为函数或方法调用的参数时,以上规则同样适用。

$foo->bar(
    $arg1,
    function($arg2)use($var1) {// body
    },
    $arg3
);

结语

本指南刻意忽略了许多风格和实践。包括但不限于:

  • 声明全局变量和全局常量。
  • 声明函数。
  • 操作符和赋值。
  • 行间对齐。
  • 注释和文档区。
  • 类名前后缀。
  • 最佳实践。

Future recommendations MAY revise and extend this guide to address those or other elements of style and practice.

附录A 调查

In writing this style guide, the group took a survey of member projects to determine common practices. The survey is retained herein for posterity.

调查数据

url,http://www.horde.org/apps/horde/docs/CODING_STANDARDS,http://pear.php.net/manual/en/standards.php,http://solarphp.com/manual/appendix-standards.style,http://framework.zend.com/manual/en/coding-standard.html,http://symfony.com/doc/2.0/contributing/code/standards.html,http://www.ppi.io/docs/coding-standards.html,https://github.com/ezsystems/ezp-next/wiki/codingstandards,http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html,https://github.com/UnionOfRAD/lithium/wiki/Spec%3A-Coding,http://drupal.org/coding-standards,http://code.google.com/p/sabredav/,http://area51.phpbb.com/docs/31x/coding-guidelines.html,https://docs.google.com/a/zikula.org/document/edit?authkey=CPCU0Us&hgd=1&id=1fcqb93Sn-hR9c0mkN6m_tyWnmEvoswKBtSc0tKkZmJA,http://www.chisimba.com,n/a,https://github.com/Respect/project-info/blob/master/coding-standards-sample.php,n/a,Object Calisthenics for PHP,http://doc.nette.org/en/coding-standard,http://flow3.typo3.org,https://github.com/propelorm/Propel2/wiki/Coding-Standards,http://developer.joomla.org/coding-standards.html
voting,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?,yes,no,yes
indent_type,4,4,4,4,4,tab,4,tab,tab,2,4,tab,4,4,4,4,4,4,tab,tab,4,tab
line_length_limit_soft,75,75,75,75,no,85,120,120,80,80,80,no,100,80,80,?,?,120,80,120,no,150
line_length_limit_hard,85,85,85,85,no,no,no,no,100,?,no,no,no,100,100,?,120,120,no,no,no,no
class_names,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,lower_under,studly,lower,studly,studly,studly,studly,?,studly,studly,studly
class_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,next,next,next,next,next,next,same,next,next
constant_names,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper
true_false_null,lower,lower,lower,lower,lower,lower,lower,lower,lower,upper,lower,lower,lower,upper,lower,lower,lower,lower,lower,upper,lower,lower
method_names,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,lower_under,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel
method_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,same,next,next,next,next,next,same,next,next
control_brace_line,same,same,same,same,same,same,next,same,same,same,same,next,same,same,next,same,same,same,same,same,same,next
control_space_after,yes,yes,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes
always_use_control_braces,yes,yes,yes,yes,yes,yes,no,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes
else_elseif_line,same,same,same,same,same,same,next,same,same,next,same,next,same,next,next,same,same,same,same,same,same,next
case_break_indent_from_switch,0/1,0/1,0/1,1/2,1/2,1/2,1/2,1/1,1/1,1/2,1/2,1/1,1/2,1/2,1/2,1/2,1/2,1/2,0/1,1/1,1/2,1/2
function_space_after,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no
closing_php_tag_required,no,no,no,no,no,no,no,no,yes,no,no,no,no,yes,no,no,no,no,no,yes,no,no
line_endings,LF,LF,LF,LF,LF,LF,LF,LF,?,LF,?,LF,LF,LF,LF,?,,LF,?,LF,LF,LF
static_or_visibility_first,static,?,static,either,either,either,visibility,visibility,visibility,either,static,either,?,visibility,?,?,either,either,visibility,visibility,static,?
control_space_parens,no,no,no,no,no,no,yes,no,no,no,no,no,no,yes,?,no,no,no,no,no,no,no
blank_line_after_php,no,no,no,no,yes,no,no,no,no,yes,yes,no,no,yes,?,yes,yes,no,yes,no,yes,no
class_method_control_brace,next/next/same,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/next,same/same/same,same/same/same,same/same/same,same/same/same,next/next/next,next/next/same,next/same/same,next/next/next,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/same,next/next/next

调查说明

indent_type: The type of indenting. tab = “Use a tab”, 2 or 4 = “number of spaces”

line_length_limit_soft: The “soft” line length limit, in characters. ? = not discernible or no response, no means no limit.

line_length_limit_hard: The “hard” line length limit, in characters. ? = not discernible or no response, no means no limit.

class_names: How classes are named. lower = lowercase only, lower_under = lowercase with underscore separators, studly = StudlyCase.

class_brace_line: Does the opening brace for a class go on the same line as the class keyword, or on the next line after it?

constant_names: How are class constants named? upper = Uppercase with underscore separators.

true_false_null: Are the true, false, and null keywords spelled as all lower case, or all upper case?

method_names: How are methods named? camel = camelCase, lower_under = lowercase with underscore separators.

method_brace_line: Does the opening brace for a method go on the same line as the method name, or on the next line?

control_brace_line: Does the opening brace for a control structure go on the same line, or on the next line?

control_space_after: Is there a space after the control structure keyword?

always_use_control_braces: Do control structures always use braces?

else_elseif_line: When using else or elseif, does it go on the same line as the previous closing brace, or does it go on the next line?

case_break_indent_from_switch: How many times are case and break indented from an opening switch statement?

function_space_after: Do function calls have a space after the function name and before the opening parenthesis?

closing_php_tag_required: In files containing only PHP, is the closing ?> tag required?

line_endings: What type of line ending is used?

static_or_visibility_first: When declaring a method, does static come first, or does the visibility come first?

control_space_parens: In a control structure expression, is there a space after the opening parenthesis and a space before the closing parenthesis? yes = if ( expr),no=if(expr).

blank_line_after_php: Is there a blank line after the opening PHP tag?

class_method_control_brace: A summary of what line the opening braces go on for classes, methods, and control structures.

调查结果

indent_type:
    tab: 72: 14: 14line_length_limit_soft:
    ?: 2
    no: 375: 480: 685: 1100: 1120: 4150: 1line_length_limit_hard:
    ?: 2
    no: 1185: 4100: 3120: 2class_names:
    ?: 1
    lower: 1
    lower_under: 1
    studly: 19class_brace_line:
    next: 16
    same: 6constant_names:
    upper: 22true_false_null:
    lower: 19
    upper: 3method_names:
    camel: 21
    lower_under: 1method_brace_line:
    next: 15
    same: 7control_brace_line:
    next: 4
    same: 18control_space_after:
    no: 2
    yes: 20always_use_control_braces:
    no: 3
    yes: 19else_elseif_line:
    next: 6
    same: 16case_break_indent_from_switch:0/1: 41/1: 41/2: 14function_space_after:
    no: 22closing_php_tag_required:
    no: 19
    yes: 3line_endings:
    ?: 5
    LF: 17static_or_visibility_first:
    ?: 5
    either: 7
    static: 4
    visibility: 6control_space_parens:
    ?: 1
    no: 19
    yes: 2blank_line_after_php:
    ?: 1
    no: 13
    yes: 8class_method_control_brace:
    next/next/next: 4
    next/next/same: 11
    next/same/same: 1
    same/same/same: 6

以上就介绍了PHP编码风格指南 (PHP-FIG PSR-2),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn