php编码
The PSR-1 and PSR-2 coding standards define how code should look like.
PSR-1和PSR-2编码标准定义了代码的外观。
PSR-1 is the basic coding standard for PHP. PSR-2 is the coding style guide.
PSR-1是PHP的基本编码标准。 PSR-2是编码样式指南。
Prior to their definition one would copy a coding standard from one of the popular frameworks around, but now that PHP has an official coding standard, we should all aim to adhere to it.
在定义它们之前,需要先从一种流行的框架中复制一种编码标准,但是由于PHP具有正式的编码标准,因此我们所有人都应该遵守该标准。
简而言之,PSR-1 (PSR-1 in a nutshell)
- Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both 文件应声明符号(类,函数,常量等)或引起副作用(例如,生成输出,更改.ini设置等),但不应两者都做
- Namespaces and classes MUST follow an “autoloading” PSR: [PSR-0, PSR-4] 命名空间和类必须遵循“自动加载” PSR:[PSR-0,PSR-4]
- Class names MUST be declared in StudlyCaps 类名必须在StudlyCaps中声明
- Method names MUST be declared in camelCase 方法名称必须在camelCase中声明
简而言之,PSR-2 (PSR-2 in a nutshell)
- Code MUST use 4 spaces for indenting, not tabs 代码必须使用4个空格来缩进,不能使用制表符
- There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less. 线长绝不能有硬性限制; 软限制必须为120个字符; 每行不得超过80个字符。
- There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declarations. 在名称空间声明之后必须有一个空白行,在使用声明块之后必须有一个空白行。
- Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility. 必须在所有属性和方法上声明可见性; 摘要和最终内容必须在可见性之前声明; 静态必须在可见性之后声明。
- Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before. 控制结构的开括号必须在其后没有空格,控制结构的闭括号必须在其前没有空格。
执行标准 (Enforcing standards)
It’s essential to know and understand the coding standards. Having your IDE or editor enforce it automatically is a big step towards complying with it.
了解和理解编码标准至关重要。 让您的IDE或编辑器自动执行它是朝着遵守它迈出的一大步。
在PHPStorm上 (On PHPStorm)
It’s built-in. Go in Preferences -> Editor -> Code Style -> PHP, on the right click “Set from..” and choose “Predefined Style” -> “PSR1/PSR2”
它是内置的。 进入“首选项”->“编辑器”->“代码样式”->“ PHP”,右键单击“设置自..”,然后选择“预定义样式”->“ PSR1 / PSR2”
崇高的文字 (On Sublime Text)
Use sublime-phpfmt
php编码