In-depth discussion on PHP coding specifications

Source: Internet
Author: User
Tags code tag drupal
This article provides a detailed analysis of PHP encoding specifications. For more information, see Indenting and Whitespace)
Use two spaces instead of the tab key for code indent (notepad ++, Eclipse and other editors support this configuration );
The end of the line should not contain white space characters
\ N (Unix line break) should be used instead of \ r \ n (Windows line break)
All files should end with a blank line

Operators)
All binary operators (operators between two values), such as +,-, = ,! =, =,>, And so on. a space must be left at both ends of the operator. for example, use $ foo = $ bar instead of $ foo = $ bar.
All unary operators (only one operator on duty), such as ++, should not contain spaces between values and operators.

Casting)
A space should be added between (type) and the variable to be transformed, such as (int) $ mynumber.
Control ures)
The control structure includes if, for, while, switch, etc. The following is a simple if statement structure example:

The code is as follows:


If (condition1 | condition2 ){
Action1;
}
Elseif (condition3 & condition4 ){
Action2;
}
Else {
Defaultaction;
}


(Note: Do not use "else if" -- always use elseif .)
There should be a space between the keyword of the control statement and the left bracket to distinguish it from the function call.
Even if braces are optional, braces should always be used. This improves code readability and reduces logical errors caused by nesting.
Switch statement structure example:

The code is as follows:


Switch (condition ){
Case 1:
Action1;
Break;
Case 2:
Action2;
Break;
Default:
Defaultaction;
}
Do-while statement structure example:
Do {
Actions;
} While ($ condition );


Line length and wrapping)
Generally, the length of each line of code should not exceed 80 characters.
In the following cases, the row length can exceed 80 characters: when the row contains too long function names, function/class definitions, variable declarations, etc.
For ease of reading and understanding, the row length of the control structure can exceed 80 characters

The code is as follows:


If ($ something ['with'] ['something'] ['else'] ['in'] ['where'] =
Mymodule_check_something ($ whatever ['else']) {
...
}
If (isset ($ something ['whe'] ['ever']) & $ something ['whe'] ['ever']> $ infinite
& User_access ('Galaxy ')){
...
}
// Non-obvious conditions of low complexity are also acceptable, but shoshould
// Always be specified ented, explaining WHY a particle check is done.
If (preg_match ('@ (/| \) (\. \. | ~) @ ', $ Target) & strpos ($ target_dir, $ repository)
! = 0 ){
Return FALSE;
}


The control condition (condition) should not write multiple lines
Control conditions should be split appropriately for reading and understanding. avoid the following situations when writing code:

The code is as follows:


// DON't do this!
If (isset ($ key )&&! Empty ($ user-> uid) & amp; $ key = $ user-> uid) | (isset ($ user-
> Cache )? $ User-> cache: '') = ip_address () | isset ($ value) & $ value> = time ()))
{
...
}


Splitting control conditions is not only easy to read, but also easy to add comments to let people know why such conditions are judged.

The code is as follows:


// Key is only valid if it matches the current user's ID, as otherwise other
// Users cocould access any user's things.
$ Is_valid_user = (isset ($ key )&&! Empty ($ user-> uid) & amp; $ 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 calling)
When a function is called, there is no space between the function name and the left parenthesis. except for the last parameter, each parameter must be followed by a space, for example:
$ Var = foo ($ bar, $ baz, $ quux );
As mentioned earlier, there should be a space on both sides of the equal sign. When there are a series of related statements, you can increase the number of spaces for readability, such:
$ Short = foo ($ bar );
$ Long_variable = foo ($ baz );

Function declaration)
Parameters that contain the default value should be placed at the end. when the function has a return value, return the value that is easy to understand as much as possible:

The code is as follows:


Function funstuff_system ($ field ){
$ System ["description"] = t ("This module inserts funny text into posts randomly .");
Return $ system [$ field];
}


Class Constructor cballs)
When a class constructor without parameters is called, brackets are always included.
$ Foo = new MyClassName ();

Class constructor with parameters
$ Foo = new MyClassName ($ arg1, $ arg2 );
If you use a variable as the class name, you must assign a value to the variable before calling the class constructor:

The code is as follows:


$ Bar = 'myclassname ';
$ Foo = new $ bar ();
$ Foo = new $ bar ($ arg1, $ arg2 );


Array)
The values of the array should be separated by spaces. The value assignment operator (=>) should also contain spaces:
$ Some_array = array ('hello', 'World', 'foo' => 'bar ');
When declaring an array with more than 80 characters in length (usually when constructing a form or menu), you should compile the branches and indentation of each element:

The 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. this is not a hand error, but avoids parsing errors due to the absence of a comma after a new element is added to the end. (To some extent, adding a comma at the end of the last array element is a recommended practice, even when submitting code to drupal.org, some code specification check scripts will prompt a warning because the last element is not added with a comma .)

Quotes)
Drupal does not have a strong standard for the use of single quotes and double quotes. you only need to keep the usage consistent within the same module.
The efficiency of using single quotes is higher than that of double quotes, because the parser does not need to look for variables between quotes. The following two situations use double quotation marks:
Variable in the middle of the quotation mark, such as "$ header"
The quotation marks are enclosed in single quotation marks. using double quotation marks can avoid escaping the single quotation marks "He's a good person. "You can also use single quotes,. the pot parser cannot handle this situation very well, and it looks strange: 'He \'s a good person.'

String Concatenations)
Spaces must be added between the vertex and the string to be connected to enhance code readability:
You can use double quotation marks to connect variables.
When using the connection assignment character (. =), spaces must be reserved on both sides of the symbol.

Comment)
The Annotation specification is discussed separately on the Doxygen and annotation format specification pages.

Including Code)
Require_once () is used for any unconditional file reference. In any case where a file is referenced with a condition, use include_once (). both statements ensure that the file is introduced only once.
When code is introduced from the current directory or subdirectory, it always starts with a vertex path
Include_once./includes/mymodule_formatting.inc
In Drupal 7 and later versions, use the DRUPAL_ROOT constant:
Require_once DRUPAL_ROOT. '/'. variable_get ('cache _ Inc', 'Des/cache. Inc ');
PHP Code tag (PHP Code Tags)
Always use To define PHP code without using . This is to comply with Drupal specifications and facilitate code reference in other systems and platforms.
Since Drupal 4.7, the last one?> The reason is as follows:
Remove it to avoid white spaces at the end of the file. these white spaces may cause "header sent (header already sent)" errors, XHTML/XML verification errors, and other problems.
The PHP Terminator at the end of the official PHP instruction is optional.
PHP.net itself also removes the final delimiter (such as prepend. inc) at the end of the file)

Semicolon (Semicolons)
The PHP language requires that, except for code blocks, most rows must end with semicolons. Drupal code specifications also have this requirement, and the same applies to code blocks. The following is an example of a single-line code block:
-- YES
-- NO
Example URL)
Use example.com to represent all examples of URLs
Naming Conventions)
Functions and Variables)
The function and variable names should use lower-case letters separated by underscores. The function should use the module Group/module name as the prefix to avoid conflicts with different modules.
Persistent Variables)
A persistent variable is a variable obtained and set through the variable_get ()/variable_set () function. the variable name should be in lowercase and separated by underscores. Persistent variables should also use the module Group/module name as the prefix to avoid conflicts with different modules.

Constant (Constants)
Constants always require full uppercase letters, and words are separated by underscores. (Including PHP built-in constants TRUE, FALSE, NULL)
The constants defined in the module must always use the upper-case module name as the prefix.
In Drupal 8 and later, use the const keyword instead of the define () function to define constants, because it is more efficient.
Note that const cannot be used in PHP expressions, so in condition judgment and non-literal nominal value (non-literal value ???) The define () function should still be used.

Global Variables)
When defining a global variable, you must start with an underscore and a module/topic name.
Class)
Class names should be named in the upper case (that is, the first letter of a word)

The method (function) and attribute (member variable) in the class should use the lower-case hump type

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.