search
HomeBackend DevelopmentPHP TutorialPSR-1 基本代码规范

基本代码规范

本篇规范制定了代码基本元素的相关标准,以确保共享的PHP代码间具有较高程度的技术互通性。

1. 概览 -----------

  • PHP代码文件 必须

  • PHP代码文件 必须以 不带BOM的 UTF-8编码;

  • PHP代码中 应该只定义类、函数、常量等声明,或其他会产生 从属效应的操作(如:生成文件输出以及修改.ini配置文件等),二者只能选其一;

  • 命名空间以及类 必须符合 PSR 的自动加载规范:PSR-0 或PSR-4 中的一个;

  • 类的命名 必须遵循 StudlyCaps大写开头的驼峰命名规范;

  • 类中的常量所有字母都 必须大写,单词间用下划线分隔;

  • 方法名称 必须符合 camelCase式的小写开头驼峰命名规范。

  1. 文件

2.1. PHP标签

PHP代码 必须使用 长标签 或 = ?>短输出标签;

一定不可使用其它自定义标签。

2.2. 字符编码

PHP代码 必须且只可使用 不带BOM的UTF-8编码。

2.3. 从属效应(副作用)

一份PHP文件中 应该要不就只定义新的声明,如类、函数或常量等不产生从属效应的操作,要不就只有会产生从属效应的逻辑操作,但 不该同时具有两者。

“从属效应”(side effects)一词的意思是,仅仅通过包含文件,不直接声明类、函数和常量等,而执行的逻辑操作。

“从属效应”包含却不仅限于:生成输出、直接的 require或 include、连接外部服务、修改 ini 配置、抛出错误或异常、修改全局或静态变量、读或写文件等。

以下是一个反例,一份包含声明以及产生从属效应的代码:

<?php// 从属效应:修改 ini 配置ini_set('error_reporting', E_ALL);// 从属效应:引入文件include "file.php";// 从属效应:生成输出echo "<html>\n";// 声明函数function foo(){    // 函数主体部分}

下面是一个范例,一份只包含声明不产生从属效应的代码:

<?php// 声明函数function foo(){    // 函数主体部分}// 条件声明**不**属于从属效应if (! function_exists('bar')) {    function bar()    {        // 函数主体部分    }}
  1. 命名空间和类

命名空间以及类的命名必须遵循 [PSR-0][].

根据规范,每个类都独立为一个文件,且命名空间至少有一个层次:顶级的组织名称(vendor name)。

类的命名必须 遵循 StudlyCaps大写开头的驼峰命名规范。

PHP 5.3及以后版本的代码 必须使用正式的命名空间。

例如:

<?php// PHP 5.3及以后版本的写法namespace Vendor\Model;class Foo{}

5.2.x及之前的版本 应该使用伪命名空间的写法,约定俗成使用顶级的组织名称(vendor name)如 Vendor_为类前缀。

<?php// 5.2.x及之前版本的写法class Vendor_Model_Foo{}
  1. 类的常量、属性和方法

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

4.1. 常量

类的常量中所有字母都 必须大写,词间以下划线分隔。

参照以下代码:

<?phpnamespace Vendor\Model;class Foo{    const VERSION = '1.0';    const DATE_APPROVED = '2012-06-01';}

4.2. 属性

类的属性命名可以遵循 大写开头的驼峰式 ( $StudlyCaps)、小写开头的驼峰式 ( $camelCase) 又或者是 下划线分隔式 ( $under_score),本规范不做强制要求,但无论遵循哪种命名方式,都 应该在一定的范围内保持一致。这个范围可以是整个团队、整个包、整个类或整个方法。

4.3. 方法

方法名称 必须符合 camelCase()式的小写开头驼峰命名规范。

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),