search
HomeBackend DevelopmentPHP TutorialPHP coding style specification detailed introduction

PHP coding style specification detailed introduction

Due to the flexibility of PHP, many people do not pay attention to a good code specification when writing code, making the already flexible PHP code look messy. In fact, the PSR specification PSR-1 and PSR-2 have defined some specifications in PHP coding. As long as we follow these specifications well, we can write very beautiful and neat code even when using a flexible scripting language. First, let’s take a look at the passed PSR specifications, and then briefly explain some of the specific requirements of the PSR-1 and PSR-2 specifications.

Passed PSR

##PSR numberNameDescription##123467

PSR-1 Basic Coding Standard

1. Open and close tags

First, the PHP code must start with Starts with a

2. Side Effects

PHP files either declare classes, interfaces, functions, etc., or perform logical operations (such as reading and writing files or sending output to the browser), but It shouldn’t be both.

3. Naming

Class naming must comply with the camel case naming convention starting with an uppercase letter. In other words, class names should start with a capital letter. There is no requirement to name properties, but they should be consistent. Method names must conform to the camelCase naming convention starting with lowercase. All letters in class constants must be capitalized, and words are separated by underscores.

PSR-2 Coding Style Specification

1. PSR-1 requires PHP code to start with

PSR-2 stipulates that pure PHP files should not end with a ?> tag, but should end with a blank line.

2. A blank line should be inserted after the namespace declaration, and there should also be a blank line after the use statement block .

Don’t make multiple use statements in the same line of code.

3. The beginning and end of the class

The class keyword, class name, and the extends and implements keywords must be on the same line. If a class implements multiple interfaces, the interface names can be on the same line of the class declaration, or they can occupy separate lines. If you choose to place these interface names on multiple lines, the first interface name must be on its own line and not follow the implements keyword. The opening brace ({) of a class should be written on its own line after the function declaration, and the closing brace (}) should also be written on its own line after the class body. That is, the class declaration looks like the following

class EarthGame extends Game implements
    Playable,    
    Savable
{ 
       //类体
}

It is also possible to put the class name on the same line as the class declaration.

class EarthGame extends Game implements Playble, Savable
{ 
    //类体
 }

4. Attribute declaration

Each attribute must have an access modifier (public, private or protected). Attributes cannot be declared using the keyword var. The specification of attribute names is already covered in PSR-1: you can use underscores, lowercase camelCase naming, or uppercase camelCase naming, but should remain consistent. (Personally recommend using lowercase camel case for attributes)

5. The beginning and end of the method

All methods must have access modifiers (public, private or protected). The access modifier must be after abstract or final and before static. Method parameters with default values ​​should be placed at the end of the parameter list.

 ●Single-line declaration
  The opening curly brace ({) of a method should be written on its own line after the method name, and the closing curly brace (}) should also be written on its own line after the method body (directly following after the method code). Method parameter lists should not start or end with spaces (i.e. they should follow the parentheses surrounding them). For each parameter, there should be a comma after the parameter name (or default value), and a space after the comma. This may sound complicated, as shown below:

final public static function generateTile(int $diamondCount, bool $polluted = false)
{
   //方法体
}

Multi-line declaration
If the method has many parameters, then a single-line method declaration is not practical. At this point we can split the parameter list so that each parameter (including type, parameter variable, default value, and comma) is on its own indented line. In this case, the closing parenthesis should be placed on the line after the parameter list, aligned with the beginning of the method declaration. The opening curly brace ({) should follow the closing parenthesis on the same line, separated by a space. The method body should start on a new line. Again, this may sound complicated, but the following example should help you understand this rule.

public function __construct(
    int $size,
    string $name,
    bool $warparound = false,
    bool $aliens = false
) {
  //方法体
 }

6. Lines and indentation

Code should be indented using 4 spaces instead of tabs. We can check the editor settings and set it to use 4 spaces instead of tabs when the tab key is pressed. Each line of code should be no longer than 120 characters.

7. Methods and function calls

There cannot be a space between the method name and the opening parentheses. The rules for parameter lists in method calls are the same as for parameter lists in method declarations. In other words, for single-line calls, there can be no spaces after the opening parenthesis or before the closing parenthesis. Each parameter should be followed by a comma and there should be a space before the next parameter. If a method call requires multiple lines of code, each parameter should be on its own line and indented, and the closing parenthesis should be on its own line.

$earthGanme = new EarthGame( 
     5,  
     'earth',
      true,
      true
 );
$earthGame::generateTile(5, true);

8. Process control

Process control keywords (if, for, while, etc.) must be followed by a space. However, there cannot be a space after the opening parenthesis. Likewise, there can be no spaces before the closing parenthesis. Therefore the content should fit snugly within the brackets. In contrast to class and (single-line) function declarations, the opening curly brace of flow control code should be on the same line as the closing parenthesis. The closing curly brace should be on a line of its own. Here's a simple example.

$title = [];
for ($x = 0; $x < $diamondCount; $x++) { 
   if ($polluted) {
        $title[] = new PollutionDecorator(new DiamondDecorator(new Plains()));
    } else {
        $title[] = new DiamondDecorator(new Plains());
    }
}
Basic coding specifications About basic specifications such as PHP tags and basic naming conventions
Coding style specifications Regulations on the position of braces and parameter lists and other coding formats
Log interface specification Provisions on log level and log recording behavior
Auto-loading specification Naming conventions for classes and namespaces, and provisions for mapping between them and file systems
Cache interface specification Regulations on cache management, including data types, cache item life cycle, error handling, etc.
HTTP message interface specification Conventions about HTTP requests and responses

The above is the detailed content of PHP coding style specification detailed introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

What is Content Security Policy (CSP) header and why is it important?What is Content Security Policy (CSP) header and why is it important?Apr 09, 2025 am 12:10 AM

CSP is important because it can prevent XSS attacks and limit resource loading, improving website security. 1.CSP is part of HTTP response headers, limiting malicious behavior through strict policies. 2. The basic usage is to only allow loading resources from the same origin. 3. Advanced usage can set more fine-grained strategies, such as allowing specific domain names to load scripts and styles. 4. Use Content-Security-Policy-Report-Only header to debug and optimize CSP policies.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

What is HTTPS and why is it crucial for web applications?What is HTTPS and why is it crucial for web applications?Apr 09, 2025 am 12:08 AM

HTTPS is a protocol that adds a security layer on the basis of HTTP, which mainly protects user privacy and data security through encrypted data. Its working principles include TLS handshake, certificate verification and encrypted communication. When implementing HTTPS, you need to pay attention to certificate management, performance impact and mixed content issues.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use