search

为了便于规范自己的代码,参考了 CodeIgniter、Laravel、PSR等相关规范,做一个PHP代码规范的小结。

[TOC] ## 文件格式

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

所有PHP文件必须使用 Unix LF (linefeed)作为行的结束符。

PHP 结束标签

所有PHP文件必须以一个空白行作为结束。

纯PHP代码文件必须省略最后的 ?>结束标签。

文件的命名

类文件的命名必须以大写字母开头,其他文件(配置文件,视图,一般的脚本文件等)的命名是全小写。另外,类文件的名称必须和类的名称保持一致。

命名空间和类的命名

  • CI框架:类名必须以大写字母开头,多个单词之间使用下划线分割,不要使用驼峰命名法。
  • RSP-1:类的命名必须 遵循 StudlyCaps大写开头的驼峰命名规范。

方法的命名

  • CI框架:类的方法应该使用全小写,并且应该明确指出该方法的功能,最好包含一个动词。 避免使用冗长的名称,多个单词之间使用下划线分割。
  • RSP-1:方法名称必须符合 camelCase() 式的小写开头驼峰命名规范。

属性的命名

  • CI框架:变量的命名规则和类方法的命名规则非常接近,使用全小写,使用下划线分割, 并且应该明确指出该变量的用途。非常短的无意义的变量只应该在 for 循环中作为迭代器使用。
  • RSP-1:类的属性命名可以遵循 大写开头的驼峰式 ( $StudlyCaps)、小写开头的驼峰式 ( $camelCase) 又或者是 下划线分隔式 ( $under_score),本规范不做强制要求,但无论遵循哪种命名方式,都应该在一定的范围内保持一致。这个范围可以是整个团队、整个包、整个类或整个方法。

注释

通常情况下,应该多写点注释,这不仅可以向那些缺乏经验的程序员描述代码的流程和意图, 而且当你几个月后再回过头来看自己的代码时仍能帮你很好的理解。 注释并没有强制规定的格式,但是我们建议以下的形式。

DocBlock风格的注释,写在类、方法和属性定义的前面,可以被 IDE 识别:

/** * Super Class * * @package Package Name * @subpackage  Subpackage * @category    Category * @author  Author Name * @link    http://example.com */class Super_class {
/** * Encodes string for use in XML * * @param   string  $str    Input string * @return  string */function xml_encode($str)
/** * Data for class manipulation * * @var array */public $data = array();

单行注释应该和代码合在一起,大块的注释和代码之间应该留一个空行。

// break up the string by newlines$parts = explode("\n", $str);// A longer comment that needs to give greater detail on what is// occurring and why can use multiple single-line comments.  Try to// keep the width reasonable, around 70 characters is the easiest to// read.  Don't hesitate to link to permanent external resources// that may provide greater detail://// http://example.com/information_about_something/in_particular/$parts = $this->foo($parts);

常量

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

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

PHP所有 关键字必须全部小写。

常量 true、 false和 null也必须全部小写。

逻辑操作符

不要使用 ||操作符,它在一些设备上看不清(可能看起来像是数字 11), 使用 &&操作符比使用 AND要好一点,但是两者都可以接受。 另外,在 !操作符的前后都应该加一个空格。

对返回值进行比较以及类型转换

有一些 PHP 函数在失败时返回 FALSE ,但是也可能会返回 "" 或 0 这样的有效值, 这些值在松散类型比较时和 FALSE 是相等的。所以当你在条件中使用这些返回值作比较时, 一定要使用严格类型比较,确保返回值确实是你想要的,而不是松散类型的其他值。

在检查你自己的返回值和变量时也要遵循这种严格的方式,必要时使用 === 和 !== 。

文件中的空格

PHP 起始标签的前面和结束标签的后面都不要留空格。

一个类一个文件

除非几个类是 紧密相关的,否则每个类应该单独使用一个文件。

空格

  • CI框架:在代码中使用制表符(tab)来代替空格,这虽然看起来是一件小事,但是使用制表符代替空格, 可以让开发者阅读你代码的时候,可以根据他们的喜好在他们的程序中自定义缩进。 此外还有一个好处是,这样文件可以更紧凑一点,也就是本来是四个空格字符, 现在只要一个制表符就可以了。
  • PSR-2:代码必须使用4个空格符而不是 tab键 进行缩进。
  • 缩进使用制表符,对齐使用空格。

代码缩进

函数和控制结构必须使用 Allman 样式括起来

字符串

字符串使用单引号引起来,当字符串中有变量时使用双引号,并且使用大括号将变量包起来。 另外,当字符串中有单引号时,也应该使用双引号,这样就不用使用转义符。

'My String'"My string {$foo}""SELECT foo FROM bar WHERE baz = 'bag'"
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)