search
HomeBackend DevelopmentPHP TutorialPHP expert shares: PHP code writing specifications, summarized very comprehensively

这篇文章主要介绍了关于php大牛分享:php代码编写的规范,总结的很全,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

一直以来,php都是Web开发中使用最频繁的编程语言,也正因为如此,众多的从业者,导致了很多不规范的代码。

PHP-FIG(PHP框架接口组织)制定了一整套完善的标准,推荐给广大的php开发使用。

一共制定了五套标准:

(PSR: PHP推荐标准)

PSR-1: 基本的代码风格;

PSR-2: 严格的代码风格;

PSR-3: 日志记录器接口;

PSR-4: 自动加载

其实还有一个PSR-0,不过已被PSR-4代替了,所以不存在 PSR-0版本。

一、PSR-1:基本代码风格

1. 标签: 必须要把php代码写在 , 或者 = 和 ?>标签中,不得使用其它格式的标签;

2. 编码: 必须采用无BOM头的UTF-8字符集,目前大多数的IDE编辑器都自动支持;

3. 类名: 必须采用驼峰式: CamelCase,这种格式也叫标题式,例如: IndexController;

4. 常量: 必须采用大写字母,多个单词之间采用下划线连接: APP_PATH;

5. 方法: 必须采用小驼峰式: camelCase(),例如: getStatus();

二、PSR-2: 严格的代码风格

1. 代码必须首先符合PSR-1的规范;

2. 缩进: 必须统一采用四个空格;

3. 换行: 必须使用UNIX换行风格;

4. 结尾: 必须要有一个空行,并且不允许有关闭标签 ?>;

5. 每行代码不超过80字符,最多不能超过120个字符;

6. 关键字全部使用小写字母,例如: true,false,use....;

7. 命名空间:后面必须紧跟一个空行;

8. use导入空间后,也必须紧跟一个空行;

9. 类的起始括号{, 必行另起一行;

10. 方法与函数的起始括号{,也必须另起一行;

11. 类中所有成员,必须声明可见性:public, protected,private;

12. 类中成员的特征: abstract, final, 必须放在可见性声明之前;

13. static 关键字,必须放在类成中的可见性声明之后;

14. 控制结构的起始括号必须与语句在同一行,例如: if () {};

15. 控制结构的参数之间,逗号之后必须要有空格,例如:($m, $n);

三、PSR-3: 日志记录接口

这个规范与前面的规范不同,它不是一个推荐标准,而是一个接口标准,规则了日志记录器可以实现的方法。

只要遵循这个标准,就必须实现以下9个方法:

<?php
namespace Psr\Log;
interface LoggerInterface
{
public function emergency($message, array $context=[]);
public function alert($message, array $context=[]);
public function critical($message, array $context=[]);
public function error($message, array $context=[]);
public function warning($message, array $context=[]);
public function notice($message, array $context=[]);
public function info($message, array $context=[]);
public function debug($message, array $context=[]);
public function log($level, $message, array $context=[]);
}

四、PSR-4: 自动加载器

1. 为什么要有自动加载器?

之前一个php脚本中,可能会加载大量的文件:

<?php 
include &#39;demo1.php&#39;;
include &#39;demo2.php&#39;;
include &#39;demo3.php&#39;;
......

有了自动加载器,就可以根据功能,按需加载。

在没有该标准之前, 我们可以通过__autoload()和spl_autoload_register()进行加载器注册,现在可以借助命名空间实现自动加载。

2. 自动加载原理

主要是将类,接口,trait等所在文件路径,与代码的命名空间进行映射,使之一一对应,赋予了命名空间第二次生命。

例如:

<?php
namespace app\controller;
class UserController
{
//代码
}

说明:

1. 类名: app\controller\UserController;

2. 类文件与类同名: app/controller/UserController.php

3. 类名与类文件名,通过命名空间进行映射:

<?php
define(&#39;ROOT_PATH&#39;, __DIR__);
spl_autoload_register(function($className){
require ROOT_PATH . &#39;/&#39; . str_replace(&#39;\\&#39;,&#39;/&#39;, $className) . &#39;.php&#39;;
});

4. 将类名与命名空间进行关联,是现代php开发框架的基础,composer也是基于此实现了组件自动加载;

更多的编程规范,可以登录php中文网(www.php.cn)查阅。

相关推荐:

关于php-fpm的进程数管理

对于PHP面向对象设计五大原则(SOLID)的总结

The above is the detailed content of PHP expert shares: PHP code writing specifications, summarized very comprehensively. For more information, please follow other related articles on the PHP Chinese website!

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft