@Chiang
2020-02-03T14:41:02.000000Z
字数 2324
阅读 528
PSR
- 标准的这一部分包括应被认为是确保共享PHP代码之间实现高水平技术互操作性所需的标准编码元素。
- 本文档中的关键字“必须”,“不得”,“必须”,“应”,“不得”,“应”,“应不”,“推荐”,“可以”和“可选”是按照RFC 2119中的描述进行解释。
- 文件只能使用
<?php
和<?=
标记。- 文件必须使用
UTF-8无BOM头
来编写PHP代码。- 文件既可以申明特征(在类,函数方法,常量,等等),也可以局部申明或引用(比如:打印输出,修改.ini配置项或文件等),当时不能两者都用.
- 命名空间和类的定义必须遵循自动加载参照PSR4
- 类的命名必须参考
StudlyCaps
- 类常量必须全是大写字符和下划线分隔符
- 方法的命名必须参考
camelCase
PHP编码必须使用长标签<?php ?>
或者短标签<?= ?>
,不允许使用其他的标签
PHP编码只能使用UTF-8无BOM头
编码格式
局部申明或引用
)一个文件中应当申明新的特征(在类,函数方法,常量中,等等),在没有局部引用或申明的前提下,或者应当执行局部申明或引用的逻辑,但是不能两者都用.
“side effects”,数组的意思是:执行逻辑不会关联 类,函数方法,常量等申明的配置,仅仅包含引入的文件
“Side effects” 包括但不限于:打印输出,request或者include调用,连接外部服务,修改ini配置,抛出错误和异常,修改全局静态参数,从一个文件读写等等.
The following is an example of a file with both declarations and side effects; i.e, an example of what to avoid:
<?php
// side effect: change ini settings
ini_set('error_reporting', E_ALL);
// side effect: loads a file
include "file.php";
// side effect: generates output
echo "<html>\n";
// declaration
function foo()
{
// function body
}
The following example is of a file that contains declarations without side effects; i.e., an example of what to emulate:
<?php
// declaration
function foo()
{
// function body
}
// conditional declaration is *not* a side effect
if (! function_exists('bar')) {
function bar()
{
// function body
}
}
Namespaces and classes MUST follow an “autoloading” PSR: [PSR-0, PSR-4].
This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name.
Class names MUST be declared in StudlyCaps.
Code written for PHP 5.3 and after MUST use formal namespaces.
For example:
<?php
// PHP 5.3 and later:
namespace Vendor\Model;
class Foo
{
}
Code written for 5.2.x and before SHOULD use the pseudo-namespacing convention of Vendor_ prefixes on class names.
<?php
// PHP 5.2.x and earlier:
class Vendor_Model_Foo
{
}
The term “class” refers to all classes, interfaces, and traits.
Class constants MUST be declared in all upper case with underscore separators. For example:
<?php
namespace Vendor\Model;
class Foo
{
const VERSION = '1.0';
const DATE_APPROVED = '2012-06-01';
}
This guide intentionally avoids any recommendation regarding the use of camelCase, or $under_score property names.
Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level.
Method names MUST be declared in camelCase().