[关闭]
@Chiang 2020-02-03T14:41:02.000000Z 字数 2324 阅读 528

PSR-1: 基本编码标准

PSR


  • 标准的这一部分包括应被认为是确保共享PHP代码之间实现高水平技术互操作性所需的标准编码元素。
  • 本文档中的关键字“必须”,“不得”,“必须”,“应”,“不得”,“应”,“应不”,“推荐”,“可以”和“可选”是按照RFC 2119中的描述进行解释。

概述

  • 文件只能使用<?php<?=标记。
  • 文件必须使用UTF-8无BOM头来编写PHP代码。
  • 文件既可以申明特征(在类,函数方法,常量,等等),也可以局部申明或引用(比如:打印输出,修改.ini配置项或文件等),当时不能两者都用.
  • 命名空间和类的定义必须遵循自动加载参照PSR4
  • 类的命名必须参考StudlyCaps
  • 类常量必须全是大写字符和下划线分隔符
  • 方法的命名必须参考camelCase

文件

php 标签

PHP编码必须使用长标签<?php ?>或者短标签<?= ?>,不允许使用其他的标签

字符编码

PHP编码只能使用UTF-8无BOM头编码格式

Side Effects (这里我的理解是:局部申明或引用)

一个文件中应当申明新的特征(在类,函数方法,常量中,等等),在没有局部引用或申明的前提下,或者应当执行局部申明或引用的逻辑,但是不能两者都用.

“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:

  1. <?php
  2. // side effect: change ini settings
  3. ini_set('error_reporting', E_ALL);
  4. // side effect: loads a file
  5. include "file.php";
  6. // side effect: generates output
  7. echo "<html>\n";
  8. // declaration
  9. function foo()
  10. {
  11. // function body
  12. }

The following example is of a file that contains declarations without side effects; i.e., an example of what to emulate:

  1. <?php
  2. // declaration
  3. function foo()
  4. {
  5. // function body
  6. }
  7. // conditional declaration is *not* a side effect
  8. if (! function_exists('bar')) {
  9. function bar()
  10. {
  11. // function body
  12. }
  13. }

命名空间和类名

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:

  1. <?php
  2. // PHP 5.3 and later:
  3. namespace Vendor\Model;
  4. class Foo
  5. {
  6. }

Code written for 5.2.x and before SHOULD use the pseudo-namespacing convention of Vendor_ prefixes on class names.

  1. <?php
  2. // PHP 5.2.x and earlier:
  3. class Vendor_Model_Foo
  4. {
  5. }

类常量,属性和方法

The term “class” refers to all classes, interfaces, and traits.

constants

Class constants MUST be declared in all upper case with underscore separators. For example:

  1. <?php
  2. namespace Vendor\Model;
  3. class Foo
  4. {
  5. const VERSION = '1.0';
  6. const DATE_APPROVED = '2012-06-01';
  7. }

Properties

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.

Methods

Method names MUST be declared in camelCase().


参考资料:
PSR-1: Basic Coding Standard
PSR-1 基础编码规范

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注