PHP编码风格指南 (PHP-FIG PSR-2)

本指南是 PSR-1 基本编码标准 的扩展。

本指罗列了通用的PHP代码格式规则和建议,意在减少不同作者的编码风格差异带来的认知障碍。

这里的风格约定衍生自若干成员项目。指南作者们在多个项目中协作,推动了这些指导条款落地。 指南的关键在于共享,而不是规则本身。

文中涉及的关键词 “MUST 必须”, “MUST NOT 必须不”, “REQUIRED 必需”, “SHALL 会”, “SHALL NOT 不会”, “SHOULD 应该”, “SHOULD NOT 不应该”, “RECOMMENDED 推荐的”, “MAY 可能”, 和 “OPTIONAL 可选的” 在RFC 2119 中有具体描述.

概览

  1. 代码必需遵循 “基础编码标准” PSR [PSR-1]。
  2. 代码缩进必须使用 4 空格,而不是tab。
  3. 行长度必须无硬性限制; 软性限制必须为120字符;应该少于等于80字。
  4. namespace声明后必须有一个空行,use声明后也必须有一个空行。
  5. 类的{ 必须在类名的下一行, }必须在body的下一行。
  6. 方法的 { 必须在方法签名的下一行,} 必须在body的下一行。
  7. 所有的属性和方法都要设置可见性; abstract和 final必须在可见性之前声明;static 必须在可见性后声明。
  8. 结构控制关键词后必须有一个空格; 方法和函数必须没有空格。
  9. 结构控制的 { 必须在同一行,} 必须在body的下一行。
  10. 结构控制的 ( 后必须有空格, 结构控制的 ) 前必须没有空格。

例子

下面是一个综合的例子,可以帮助你对规则有一个概略的认识。

<?php
namespace Vendor\Package;

use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class Foo extends Bar implements FooInterface
{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }

    final public static function bar()
    {
        // 方法 body
    }
}

基本规则

基本编码标准

代码必须遵循PSR-1的条款。

文件

  1. 所有文件必须使用 Unix LF (linefeed) 换行。
  2. 所有PHP文件必须使用单个空行结束。
  3. 只包含PHP的代码必须忽略php结束标记 ? >。

  1. 行长度必须没有硬性限制。
  2. 长度的软性限制必须为120字符;自动代码风格检查必须将120字设置为警告,必须不能设置为错误。
  3. 行不应该超过80字符;超过这个长度的行应该切分为多个不超过80字符的行。
  4. 非空行的结束必须没有尾随空格。
  5. 为增强可读性,可增加空行来标志代码的关联性。
  6. 每行包含的语句必须不能超过1条。

缩进

  1. 代码必须使用 4 空格的缩进, 必须不用tab作为缩进。

注意:只使用空格,不用tab,有助于避免diffs,patches, history和annotations的问题。使用空格也有助于对齐。

关键词(保留字) 和 true/false/null

  1. PHP保留字必须小写.
  2. PHP常量 true, false和 null 必须小写.

Namespace 和 Use 声明

  1. namespace 声明之后必须有空行。
  2. 所有use 声明,必须在namespace声明之后。
  3. 每个声明必须单独使用一个use。
  4. use声明区之后必须有一个空行。

例如:

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

// ... additional PHP code ...

类, 属性 和 方法

这里的“类”包括 class、interface 和 trait。

继承 和 实现

extends 和 implements 关键字必须和类名在同一行声明。

类的 { 必须独占一行; } 必须在body的下一行。

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements \ArrayAccess, \Countable
{
    // constants, properties, methods
}

implements 多个接口时,接口列表可以被分到多行,每个子行有一个缩进。如果这么做,第一个接口必须在implements 下一行,每行只能有一个接口。

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements
    \ArrayAccess,
    \Countable,
    \Serializable
{
    // constants, properties, methods
}

属性

所有属性都必须声明 visibility(可见性)。

Var 关键字必须不能用于声明属性。

每行必须只声明一个属性。

不应该通过前缀下划线来标示protected和private的属性。

例:

<?php
namespace Vendor\Package;

class ClassName
{
    public $foo = null;
}

方法

所有方法都必须声明可见性。

不应该通过前缀下划线来标示protected和private的方法。

声明方法时,方法名的后必须没有空格。 { 必须在同一行, } 必须在body的下一行。 (后必须没有空格,) 前必须没有空格。

一个方法声明的例子如下,注意 小括号,逗号,空格 和 花括号 的位置:

<?php
namespace Vendor\Package;

class ClassName
{
    public function fooBarBaz($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}

方法参数

方法的形参列表中, 每个逗号前必须没有空格。有默认值的参数必须在参数列表的最后。

<?php
namespace Vendor\Package;

class ClassName
{
    public function foo($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}

参数列表可以切分为多行,每个子行要有一个缩进。如果这么做,第一个参数必须独占一行,每行只能有一个参数。

参数列表切分为多行时,右括号)和左花括号{必须在同一行,之前必须有一个空格。

<?php
namespace Vendor\Package;

class ClassName
{
    public function aVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {
        // method body
    }
}

abstract, final 和 static

abstract和final声明必须在可见性之前声明。

static声明必须在可见性之后。

<?php
namespace Vendor\Package;

abstract class ClassName
{
    protected static $foo;

    abstract protected function zim();

    final public static function bar()
    {
        // method body
    }
}

方法和函数调用

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

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

控制结构

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

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

if, elseif, else

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

<?php
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

<?php
switch ($expr) {
    case 0:
        echo ‘First case, with a break‘;
        break;
    case 1:
        echo ‘Second case, which falls through‘;
        // no break
    case 2:
    case 3:
    case 4:
        echo ‘Third case, return instead of break‘;
        return;
    default:
        echo ‘Default case‘;
        break;
}

while, do while

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

<?php
while ($expr) {
    // structure body
}

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

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

for

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

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

foreach

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

<?php
foreach ($iterable as $key => $value) {
    // foreach body
}

try, catch

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

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

Closure 闭包

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

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

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

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

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

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

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

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

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

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

例子:

<?php
$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
};

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

<?php
$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: 7
    2: 1
    4: 14
line_length_limit_soft:
    ?: 2
    no: 3
    75: 4
    80: 6
    85: 1
    100: 1
    120: 4
    150: 1
line_length_limit_hard:
    ?: 2
    no: 11
    85: 4
    100: 3
    120: 2
class_names:
    ?: 1
    lower: 1
    lower_under: 1
    studly: 19
class_brace_line:
    next: 16
    same: 6
constant_names:
    upper: 22
true_false_null:
    lower: 19
    upper: 3
method_names:
    camel: 21
    lower_under: 1
method_brace_line:
    next: 15
    same: 7
control_brace_line:
    next: 4
    same: 18
control_space_after:
    no: 2
    yes: 20
always_use_control_braces:
    no: 3
    yes: 19
else_elseif_line:
    next: 6
    same: 16
case_break_indent_from_switch:
    0/1: 4
    1/1: 4
    1/2: 14
function_space_after:
    no: 22
closing_php_tag_required:
    no: 19
    yes: 3
line_endings:
    ?: 5
    LF: 17
static_or_visibility_first:
    ?: 5
    either: 7
    static: 4
    visibility: 6
control_space_parens:
    ?: 1
    no: 19
    yes: 2
blank_line_after_php:
    ?: 1
    no: 13
    yes: 8
class_method_control_brace:
    next/next/next: 4
    next/next/same: 11
    next/same/same: 1
    same/same/same: 6
时间: 2024-08-03 11:28:13

PHP编码风格指南 (PHP-FIG PSR-2)的相关文章

来自 Google 的 R 语言编码风格指南

本文转自Xiao Nan的博客 R语言是一门主要用于统计计算和绘图的高级编程语言. 这份 R 语言编码风格指南旨在让我们的 R 代码更容易阅读.分享和检查. 以下规则系与 Google 的 R 用户群体协同设计而成. 概要: R编码风格约定 文件命名: 以 .R (大写) 结尾 标识符命名: variable.name, FunctionName, kConstantName 单行长度: 不超过 80 个字符 缩进: 两个空格, 不使用制表符 空白 花括号: 前括号不折行写, 后括号独占一行 赋

JavaScript 编码风格指南

A.1  缩进 // 4个空格的层级缩进 if (true) { doSomething(); } A.2  行的长度 // 每行限于80个字符,超出则在运算符后换行,缩进2个层级(8个空格) doSomething(argument1, argument2, argument3, argument4, argument5); A.3  原始值 // 字符串使用双引号及长字符串的链接 var name = "Nicholas", longStr = "this is a lo

R 语言编码风格指南

R 语言是一门主要用于统计计算和绘图的高级编程语言.这份 R 语言编码风格指南旨在让我们的 R代码更容易阅读.分享和检查.以下规则系与 Google 的 R 用户群体协同设计而成. 概要: R编码风格约定 文件命名: 以 .R (大写) 结尾 标识符命名: variable.name, FunctionName, kConstantName 单行长度: 不超过 80 个字符 缩进: 两个空格, 不使用制表符 空白 花括号: 前括号不折行写, 后括号独占一行 赋值符号: 使用 <-, 而非 = 分

【翻译】Ext JS——高效的编码风格指南

原文:ExtJS - Efficient coding style guide 作者:Raja 切勿使用"new"关键字:在Ext JS中,使用"new"关键字来创建一个组件或类的实例是一种错误的做法,因为这没有遵循组件的生命周期.应该使用Ext.create方法来创建对象,例如: 错误: var obj = new Ext.panel.Panel(); 正确: var obj = Ext.create('Ext.panel.Panel'); 初始化直接量:不要直接

【翻译】EXTJS 编码风格指南与实例

原文:EXTJS Code Style Guide with examples Ext JS风格指南: 熟知的且易于学习 快速开发,易于调试,轻松部署 组织良好.可扩展和可维护 Ext JS应用程序的命名约定: 1.类 类名应使用驼峰命名(CamelCased).不要使用下划线,或其他连接字符.如:MyCustomClass 不是通过Sencha分发的类,永远不要使用Ext作为顶层命名空间.在类名中,应至少使用一次点号来划分命名空间.如TopLevelNamespace.MyClassName

(转)PEP 8——Python编码风格指南

PEP 8--Python编码风格指南标签(空格分隔): Python PEP8 编码规范原文:https://lizhe2004.gitbooks.io/code-style-guideline-cn/content/python/python-pep8.html https://python.freelycode.com/contribution/detail/47------PEP8中文版 -- Python编码风格指南(上,中,下) https://python.freelycode.c

JavaScript编码风格指南(中文版)

前言:程序语言的编码风格对于一个长期维护的软件非常重要,特别是在团队协作中.如果一个团队使用统一规范的编码分风格,可以提高团队的协作水平和工作效率.编程风格指南的核心是基本的格式化规则,这些规则决定了如何编写高水准的代码.本指南来自于<编写可维护的JavaScript>这本书,基于"Java语言编码规范"和Crockford的JavaScript编程规范,还有Nicbolas的一些个人经验和喜好.写作本文旨在加深自己印象,也为了更多人的了解到JS编码风格,提高自己的编码质量

[CoffeeScript]编码风格指南

?? 这份指南阐述了一些 CoffeeScript 的最佳实践和编码惯例. 这份指南是社群驱动的,非常鼓励大家来贡献内容. 请注意这还是一份正在完善的指南:仍有很多地方可以改进,有些已制定的准则也不一定是社区惯用的(基于此,在适当的情况下,这些有待斟酌的准则将有可能被修改或删除.) 灵感 本指南中的很多细节受到了几份现有的风格指南和其他资源的启发.特别是: PEP-8: Style Guide for Python Code Bozhidar Batsov's Ruby Style Guide

《编写可维护的 Javascript》读书笔记(附录 A 部分):Javascript 编码风格指南(1)原始值

记录一下比较有用的编码规范(该指南是基于 Java 语言编码规范和 Javascript 编程规范,同时结合作者 Nicholos Zakas 的个人经验和喜好). 一些关于格式(包括缩进.行的长度.运算符间距.括号间距.对象直接量.注释.单行注释.多行注释等类似的规范)的规范这里不做记录. A.3 原始值 // 好的写法 var name = "Nicholos"; // 不好的写法:单引号 var name = 'Nicholos'; // 不好的写法:字符串结束之前换行 var