search
HomeBackend DevelopmentPHP TutorialPHP-FIG PSR-1 # 基本编码标准

本标准包含了 对 用于保障 PHP共享代码的互操作性 的标准编码元素。

The key words “MUST 必须”, “MUST NOT 必须不”, “REQUIRED 需要”, “SHALL 将要”, “SHALL NOT 将不”, “SHOULD 应该”, “SHOULD NOT不应该”, “RECOMMENDED 推荐的”, “MAY 可以”, and “OPTIONAL 可选的” in this document are to be interpreted as described in RFC 2119.

概览
  1. 文件 必须 使用
  2. 文件中的PHP代码 必须 使用无BOM头 UTF-8编码。
  3. 文件即可以声明“符号”(诸如 类、函数、常量等),也可做一些边际效应的事情 (诸如产生输出, 改变ini设置等.)。 但这两类事情不应出现在同一个文件里。
  4. 命名空间 和 类 必须遵循“autoloading” PSR: [PSR-0, PSR-4]。
  5. 类名必须使用 StudlyCaps (首字母大写的驼峰)声明。
  6. 类常量必须使用下划线分割的大写字母。
  7. 方法名必须使用驼峰声明。
文件

PHP 标签

PHP 代码必须使用长标签 或 echo短标签 ; 必须不能使用其他形态的标签.

字符编码

PHP代码必须使用无BOM头UTF-8编码

边际效应

一个文件 (应该)要么声明符号(类、函数和常量等),不能引起任何边际效应;要么执行产生边际效应的代码。这两种情况不能出现在一个文件中。
“边际效应” 执行与声明类、函数、常量无关的逻辑。

“边际效应” 包括但不限于: 生成输出, 显式的require或include, 连接外部服务, 修改ini配置, 发出 errors 或 exceptions, 修改全局或静态变量, 读写文件 等等.

以下是一个即声明符号,又产生边际效应的例子; 这是应该要避免的情况:

<?php// 边际效应: 修改 ini 设置ini_set('error_reporting', E_ALL);// 边际效应: 加载文件include "file.php";// 边际效应: 生成输出echo "<html>\n";// 声明function foo() {    // function body}

以下例子只包含声明,无边际效应;值得效仿:

<?php// declarationfunction foo() {    // function body}// 条件式声明 不是边际效应if (! function_exists('bar')) {    function bar() {        // function body    }}
命名空间名和类名

命名空间名和类名必须遵循 “autoloading” PSR: [PSR-0, PSR-4].

这意味着每个文件只能包含一个类, 并且至少有一层命名空间: 顶级的 vendor 名.

类名必须使用 StudlyCaps (首字母大写驼峰) 声明.

针对 PHP 5.3 及以后版本的代码,必须使用正式的命名空间(5.3之前PHP不支持namespace).

例如:

<?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{}
类常量、属性和方法

这里的“类”包括 classes, interfaces 和 traits.

4.1. 常量

类常量必须使用下划线分割的大写声明。

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

属性

本指南特意避免偏向 StudlyCaps, camelCase 和 $under_score 中任意一种属性命名风格.

无论在用哪种命名风格,在合理的范围内均应改保持一致。 范围可以使 vendor-level, package-level, class-level, 或 method-level。

方法

方法名必须使用驼峰 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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor