search
HomeBackend DevelopmentPHP TutorialPSR-2 代码风格规范

代码风格规范

本篇规范是PSR-1 基本代码规范的继承与扩展。

本规范希望通过制定一系列规范化PHP代码的规则,以减少在浏览不同作者的代码时,因代码风格的不同而造成不便。

当多名程序员在多个项目中合作时,就需要一个共同的编码规范,

而本文中的风格规范源自于多个不同项目代码风格的共同特性,

因此,本规范的价值在于我们都遵循这个编码风格,而不是在于它本身。

  1. 概览
  • 代码 必须遵循PSR-1 中的编码规范 。

  • 代码 必须使用4个空格符而不是 tab键 进行缩进。

  • 每行的字符数 应该软性保持在80个之内, 理论上 一定不可多于120个, 但 一定不能有硬性限制。

  • 每个 namespace命名空间声明语句和 use声明语句块后面, 必须插入一个空白行。

  • 类的开始花括号( {) 必须写在函数声明后自成一行,结束花括号( })也 必须写在函数主体后自成一行。

  • 方法的开始花括号( {) 必须写在函数声明后自成一行,结束花括号( })也 必须写在函数主体后自成一行。

  • 类的属性和方法 必须添加访问修饰符( private、 protected以及 public), abstract以及 final 必须声明在访问修饰符之前,而 static 必须声明在访问修饰符之后。

  • 控制结构的关键字后 必须要有一个空格符,而调用方法或函数时则 一定不能有。

  • 控制结构的开始花括号( {) 必须写在声明的同一行,而结束花括号( }) 必须写在主体后自成一行。

  • 控制结构的开始左括号后和结束右括号前,都 一定不能有空格符。

1.1. 例子

以下例子程序简单地展示了以上大部分规范:

<?phpnamespace 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()    {        // method body    }}
  1. 通则

2.1 基本编码准则

代码 必须符合PSR-1 中的所有规范。

2.2 文件

所有PHP文件 必须使用 Unix LF (linefeed)作为行的结束符。

所有PHP文件 必须以一个空白行作为结束。

纯PHP代码文件 必须省略最后的 ?>结束标签。

2.3. 行

行的长度 一定不能有硬性的约束。

软性的长度约束 一定要限制在120个字符以内,若超过此长度,带代码规范检查的编辑器 一定要发出警告,不过 一定不可发出错误提示。

每行 不应该多于80个字符,大于80字符的行 应该折成多行。

非空行后 一定不能有多余的空格符。

空行 可以使得阅读代码更加方便以及有助于代码的分块。

每行 一定不能存在多于一条语句。

2.4. 缩进

代码 必须使用4个空格符的缩进, 一定不能用 tab键 。

备注: 使用空格而不是tab键缩进的好处在于,

避免在比较代码差异、打补丁、重阅代码以及注释时产生混淆。

并且,使用空格缩进,让对齐变得更方便。

2.5. 关键字 以及 True/False/Null

PHP所有 关键字 必须全部小写。

常量 true、 false和 null也 必须全部小写。

  1. namespace 以及 use 声明

namespace声明后 必须 插入一个空白行。

所有 use必须 在 namespace后声明。

每条 use声明语句 必须 只有一个 use关键词。

use声明语句块后 必须 要有一个空白行。

例如:

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;// ... additional PHP code ...
  1. 类、属性和方法

此处的“类”泛指所有的class类、接口以及traits可复用代码块。

4.1. 扩展与继承

关键词 extends和 implements 必须写在类名称的同一行。

类的开始花括号 必须独占一行,结束花括号也 必须在类主体后独占一行。

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;class ClassName extends ParentClass implements \ArrayAccess, \Countable{    // constants, properties, methods}

implements的继承列表也 可以分成多行,这样的话,每个继承接口名称都 必须分开独立成行,包括第一个。

<?phpnamespace Vendor\Package;use FooClass;use BarClass as Bar;use OtherVendor\OtherPackage\BazClass;class ClassName extends ParentClass implements    \ArrayAccess,    \Countable,    \Serializable{    // constants, properties, methods}

4.2. 属性

每个属性都 必须添加访问修饰符。

一定不可使用关键字 var声明一个属性。

每条语句 一定不可定义超过一个属性。

不要使用下划线作为前缀,来区分属性是 protected 或 private。

以下是属性声明的一个范例:

<?phpnamespace Vendor\Package;class ClassName{    public $foo = null;}

4.3. 方法

所有方法都 必须添加访问修饰符。

不要使用下划线作为前缀,来区分方法是 protected 或 private。

方法名称后 一定不能有空格符,其开始花括号 必须独占一行,结束花括号也 必须在方法主体后单独成一行。参数左括号后和右括号前 一定不能有空格。

一个标准的方法声明可参照以下范例,留意其括号、逗号、空格以及花括号的位置。

<?phpnamespace Vendor\Package;class ClassName{    public function fooBarBaz($arg1, &$arg2, $arg3 = [])    {        // method body    }}

4.4. 方法的参数

参数列表中,每个逗号后面 必须要有一个空格,而逗号前面 一定不能有空格。

有默认值的参数, 必须放到参数列表的末尾。

<?phpnamespace Vendor\Package;class ClassName{    public function foo($arg1, &$arg2, $arg3 = [])    {        // method body    }}

参数列表 可以分列成多行,这样,包括第一个参数在内的每个参数都 必须单独成行。

拆分成多行的参数列表后,结束括号以及方法开始花括号 必须 写在同一行,中间用一个空格分隔。

<?phpnamespace Vendor\Package;class ClassName{    public function aVeryLongMethodName(        ClassTypeHint $arg1,        &$arg2,        array $arg3 = []    ) {        // method body    }}

4.5. abstract、 final、 以及 static

需要添加 abstract或 final声明时, 必须写在访问修饰符前,而 static则 必须写在其后。

<?phpnamespace Vendor\Package;abstract class ClassName{    protected static $foo;    abstract protected function zim();    final public static function bar()    {        // method body    }}

4.6. 方法及函数调用

方法及函数调用时,方法名或函数名与参数左括号之间 一定不能有空格,参数右括号前也 一定不能有空格。每个参数前 一定不能有空格,但其后 必须有一个空格。

<?phpbar();$foo->bar($arg1);Foo::bar($arg2, $arg3);

参数 可以分列成多行,此时包括第一个参数在内的每个参数都 必须单独成行。

<?php$foo->bar(    $longArgument,    $longerArgument,    $muchLongerArgument);
  1. 控制结构

控制结构的基本规范如下:

  • 控制结构关键词后 必须有一个空格。
  • 左括号 (后 一定不能有空格。
  • 右括号 )前也 一定不能有空格。
  • 右括号 )与开始花括号 {间 一定有一个空格。
  • 结构体主体 一定要有一次缩进。
  • 结束花括号 } 一定在结构体主体后单独成行。

每个结构体的主体都 必须被包含在成对的花括号之中,

这能让结构体更加结构话,以及减少加入新行时,出错的可能性。

5.1. if、 elseif和 else

标准的 if结构如下代码所示,留意 括号、空格以及花括号的位置,

注意 else和 elseif都与前面的结束花括号在同一行。

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

应该使用关键词 elseif代替所有 else if,以使得所有的控制关键字都像是单独的一个词。

5.2. switch和 case

标准的 switch结构如下代码所示,留意括号、空格以及花括号的位置。

case语句 必须相对 switch进行一次缩进,而 break语句以及 case内的其它语句都 必须 相对 case进行一次缩进。

如果存在非空的 case直穿语句,主体里必须有类似 // no break的注释。

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

5.3. while和 do while

一个规范的 while语句应该如下所示,注意其 括号、空格以及花括号的位置。

<?phpwhile ($expr) {    // structure body}

标准的 do while语句如下所示,同样的,注意其 括号、空格以及花括号的位置。

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

5.4. for

标准的 for语句如下所示,注意其 括号、空格以及花括号的位置。

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

5.5. foreach

标准的 foreach语句如下所示,注意其 括号、空格以及花括号的位置。

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

5.6. try, catch

标准的 try catch语句如下所示,注意其 括号、空格以及花括号的位置。

<?phptry {    // try body} catch (FirstExceptionType $e) {    // catch body} catch (OtherExceptionType $e) {    // catch body}
  1. 闭包

闭包声明时,关键词 function后以及关键词 use的前后都 必须要有一个空格。

开始花括号 必须写在声明的同一行,结束花括号 必须紧跟主体结束的下一行。

参数列表和变量列表的左括号后以及右括号前, 必须不能有空格。

参数和变量列表中,逗号前 必须不能有空格,而逗号后 必须要有空格。

闭包中有默认值的参数 必须放到列表的后面。

标准的闭包声明语句如下所示,注意其 括号、逗号、空格以及花括号的位置。

<?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);
  1. 总结

以上规范难免有疏忽,其中包括但不仅限于:

  • 全局变量和常量的定义

  • 函数的定义

  • 操作符和赋值

  • 行内对齐

  • 注释和文档描述块

  • 类名的前缀及后缀

  • 最佳实践

本规范之后的修订与扩展将弥补以上不足。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor