Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the PHP coding specification?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "what the PHP coding specification is like", the content is simple and clear, and I hope it can help you solve your doubts. Let the editor lead you to study and learn what the PHP coding specification is like.

Indentation and white space characters (Indenting and Whitespace)

Use 2 spaces for code indentation without using the tab key (this configuration is supported by editors such as notepad++, Eclipse)

There should be no white space characters at the end of the line

Use\ n (Unix newline character) instead of\ r\ n (Windows newline character)

All files should end with a blank line

Operator (Operators)

All binary operators (operators between two values), such as +, -, =,! =, = =, >, etc., need to have a space on both ends of the operator, such as $foo=$bar instead of $foo=$bar.

All unary operators (operators that operate only one duty), such as +, should not add spaces between values and operators

Transformation (Casting)

A space should be added between (type) and the variable to be transformed, such as (int) $mynumber.

Control structure (Control Structures)

The control structure includes if, for, while, switch, and so on. Here is an example of a simple if statement structure:

The copy code is as follows:

If (condition1 | | condition2) {

Action1

}

Elseif (condition3 & & condition4) {

Action2

}

Else {

Defaultaction

}

(Note: don't use "elseif"-- always use elseif.)

There should be a space between the keyword of the control statement and the left parenthesis to distinguish it from the function call.

You should always use curly braces even when curly braces are optional. This enhances the readability of the code and reduces logic errors caused by nesting.

Example of switch statement structure:

The copy code is as follows:

Switch (condition) {

Case 1:

Action1

Break

Case 2:

Action2

Break

Default:

Defaultaction

}

Example of do-while statement structure:

Do {

Actions

} while ($condition)

Line length and Encapsulation (Line length and wrapping)

In general, each line of code should not exceed 80 characters in length

In the following cases, the line length can exceed 80 characters: when the line contains overly long function names, function / class definitions, variable declarations, etc.

For ease of reading and understanding, the line length of the control structure can exceed 80 characters

The copy code is as follows:

If ($something ['with'] [' something'] ['else'] [' in'] ['here'] = =

Mymodule_check_something ($whatever ['else'])) {

...

}

If (isset ($something ['what'] [' ever']) & $something ['what'] [' ever'] > $infinite

& & user_access ('galaxy')) {

...

}

/ / Non-obvious conditions of low complexity are also acceptable, but should

/ / always be documented, explaining WHY a particular check is done.

If (preg_match ('@ (/ |\) (\.\. | ~) @', $target) & & strpos ($target_dir, $repository)

! = 0) {

Return FALSE

}

Control conditions (condition) should not write multiple lines

The control conditions should be split properly to make it easier to read and understand, and the following situations should be avoided when writing code:

The copy code is as follows:

/ / DON'T DO THIS!

If ((isset ($key) & &! empty ($user- > uid) & & $key = = $user- > uid) | (isset ($user-)

> cache)? $user- > cache:') = = ip_address () | | isset ($value) & & $value > = time ()

{

...

}

Splitting the control condition is not only easy to read, but also convenient to add notes to let people know why such a condition judgment is made.

The copy code is as follows:

/ / Key is only valid if it matches the current user's ID, as otherwise other

/ / users could access any user's things.

$is_valid_user = (isset ($key) & &! empty ($user- > uid) & & $key = = $user- > uid)

/ / IP must match the cache to prevent session spoofing.

$is_valid_cache = (isset ($user- > cache)? $user- > cache = = ip_address (): FALSE)

/ / Alternatively, if the request query parameter is in the future, then it

/ / is always valid, because the galaxy will implode and collapse anyway.

$is_valid_query = $is_valid_cache | | (isset ($value) & & $value > = time ())

If ($is_valid_user | | $is_valid_query) {

...

}

Function call (Function Calls)

When calling a function, there is no space between the function name and the left parenthesis, except for the last parameter, each parameter should be followed by a space, such as:

$var = foo ($bar, $baz, $quux)

As mentioned before, there should be a space on each side of the equal sign. When there are a series of related statements, for readability, you can appropriately increase the number of spaces, such as:

$short = foo ($bar)

$long_variable = foo ($baz)

Function declaration (Function Declarations)

The parameter containing the default value should be placed last, and when the function has a return value, try to return a value that is easy to understand:

The copy code is as follows:

Function funstuff_system ($field) {

$system ["description"] = t ("This module inserts funny text into posts randomly.")

Return $system [$field]

}

Class constructor call (Class Constructor Calls)

Always include parentheses when calling a class constructor with no arguments

$foo = new MyClassName ()

Class constructor with parameters

$foo = new MyClassName ($arg1, $arg2)

If you use a variable as the class name, you need to assign a value to the variable before calling the class constructor:

The copy code is as follows:

$bar = 'MyClassName'

Foo = new $bar ()

$foo = new $bar ($arg1, $arg2)

Array (Array)

The values of the array should be separated by spaces, and the assignment operation symbol (= >) should also contain spaces:

$some_array = array ('hello',' world', 'foo' = >' bar')

When the character length of a declared array is more than 80 characters (usually when constructing forms and menus), you should break the elements and indent them:

The copy code is as follows:

$form ['title'] = array (

'# type' = >' textfield'

'# title' = > t (' Title')

'# size' = > 60

'# maxlength' = > 128

'# description' = > t (' The title of your node.')

);

Note: there is a comma at the end of the last array element, which is not a manual error, but to avoid parsing errors due to the lack of commas after new elements are added to the end. (to some extent, it is recommended to put a comma at the end of the last array element, and even when submitting code to drupal.org, some code specification detection scripts will give you a warning because the last element did not add a comma. )

Quotation marks (Quotes)

Drupal does not have a very strong standard for the use of single and double quotes, just keep the usage uniform in the same module.

Using single quotation marks is more efficient than double quotation marks because the parser does not need to look for variables between quotation marks. Here are two cases in which double quotation marks are used:

The quotation marks are surrounded by variables, such as "$header"

There are single quotation marks in the middle of the quotation marks, and the use of double quotation marks can avoid the escape of "He's a good person." Of course, you can also use single quotes, but the .pot parser doesn't handle this situation very well, and it looks like a strange'He\'s a good person.'.

String concatenation (String Concatenations)

You need to add a space between the point and the string to concatenate to enhance the readability of the code:

If you simply connect variables, you can use double quotes

When using the connection assignment (. =), you need to reserve spaces on both sides of the symbol

Comments (Comment)

Annotation specifications are discussed separately on the Doxygen and annotation format specification pages

Bring in Code (Including Code)

In any case where a file is referenced unconditionally, use require_once (), and in any case where a file is conditionally referenced, use include_once (). Both statements ensure that the file is introduced only once.

When code is brought in from the current directory or subdirectory, it always starts with a dot path

Include_once. / includes/mymodule_formatting.inc

In Drupal 7 and later, use the DRUPAL_ROOT constant:

Require_once DRUPAL_ROOT. '/'. Variable_get ('cache_inc',' includes/cache.inc')

PHP Code tag (PHP Code Tags)

Always use to define PHP code without using to. This is to comply with the Drupal specification and to make it easier for code to be referenced in other systems and platforms.

Since Drupal 4.7, the last? > has been deliberately ignored for the following reasons:

Remove it to avoid white space characters at the end of the file, which can cause "header sent (header already sent)" errors, XHTML/XML validation errors, and other problems.

The PHP delimiter at the end of the PHP official description is optional

PHP.net itself also removes the delimiter at the end of the file (such as prepend.inc)

Semicolon (Semicolons)

The PHP language requires that most lines, except for code blocks, be followed by a semicolon. The Drupal code specification also requires this, and the same is true for code blocks. The following is an example of a single-line code block:

-- YES

-- NO

Example URL (Example URL)

Use example.com to represent all sample URLs

Naming Convention (Naming Conventions)

Functions and variables (Functions and Variables)

Function and variable names should be in lowercase letters, and words should be separated by underscores. The function should be prefixed with the module group / module name to avoid conflicts with different modules.

Persistent variable (Persistent Variables)

Persistent variables are variables that are obtained and set through the variable_get () / variable_set () function. Variable names should be in lowercase letters and words should be separated by underscores. Persistent variables should also be prefixed with module group / module names to avoid conflicts with different modules.

Constant (Constants)

Constants always require all uppercase letters, and words are separated by underscores. (including PHP built-in constants TRUE, FALSE, NULL)

Constants defined in a module should always be prefixed with an uppercase module name.

In and after Drupal 8, you should use the const keyword instead of the define () function to define constants because it is more efficient

Note that const cannot be used for PHP expressions, so the define () function should still be used for conditional judgment and non-literal values (non-literal value).

Global variable (Global Variables)

When defining global variables, you should start with an underscore plus a module / topic name

Class (Class)

Class names should be named in a hump style (that is, the first letter of the word is capitalized)

Methods (functions) and properties (member variables) in classes should use humps with lowercase initials

When defining access permissions, use protected instead of private, so that other classes can extend and update methods as necessary. Protected and public functions and variables should not begin with an underscore.

More about object-oriented coding specifications

File name (Filename)

All document files should be suffixed with .txt for easy viewing by Windows users. At the same time, all file names should be uppercase and file suffixes should be all lowercase.

Such as README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt and so on.

Auxiliary modules and tools

Coder module: can follow some of the above code specifications, review and modify the code

Drupal Code Sniffer: code specification detection tool

PAReview.sh: also handles the code specification detection script in sandboxie, strictly complies with almost all of the above code specifications and gives suggestions for modification.

The above is all the content of this article "what is the PHP coding specification?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report