An in-depth discussion of PHP coding specifications _php Skills

Source: Internet
Author: User
Tags class definition php language lowercase naming convention drupal

Indents and whitespace characters (indenting and whitespace)
Code indents using 2 spaces without the TAB key (notepad++, which are supported by editors such as Eclipse);
There should be no whitespace characters at the end of the line
should use \ n (Unix newline character) instead of \ r \ n (Windows line break)
All files should end with a blank line

Operator (Operators)
All two-dollar operators (operators between two values), such as +,-, =,!=, = =, >, and so on, leave a space at both ends of the operator, such as $foo = $bar instead of $foo = $bar.
All unary operators (only one operator on duty), such as + +, where no spaces should be added 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 (structures)
The control structure contains if, for, while, switch, and so on, the following is a simple example of an IF statement structure:

Copy Code code 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 parenthesis to differentiate it from the function call.
You should always use curly braces even when curly braces are optional. This strengthens the readability of your code and reduces the logic errors that result from nesting.
Switch Statement Structure example:
Copy Code code as follows:

Switch (condition) {
Case 1:
Action1;
Break
Case 2:
Action2;
Break
Default
DefaultAction;
}
DO-WHILE Statement Structure Example:
do {
Actions
while ($condition);

row length and encapsulation (line length and wrapping)
Typically, the length of each line of code should not exceed 80 characters
The row length can exceed 80 characters if the row contains an too long function name, function/class definition, variable declaration, and so on
To facilitate reading and understanding, the length of the control structure can exceed 80 characters
Copy Code code as follows:

if ($something [' and '] [' 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 are done.
if (Preg_match (/|\\) (\.\.| ~) @ ', $target) && Strpos ($target _dir, $repository)
!== 0) {
return FALSE;
}

control conditions (condition) should not write multiple lines
Control conditions should be split properly to facilitate reading and understanding, and when writing code, avoid the following situations:
Copy Code code 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 control conditions is not only easy to read, but also makes it easy to add comments that let people know why such conditions are judged
Copy Code code as follows:

The Key is only valid if it matches the current user ' s ID, as otherwise
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 would implode and collapse anyway.
$is _valid_query = $is _valid_cache | | (Isset ($value) && $value >= Time ());
if ($is _valid_user | | $is _valid_query) {
...
}

functions Call (function Calls)
When calling a function, there is no space between the function name and the left parenthesis, except for the last argument, each parameter should be followed by a space, such as:
$var = foo ($bar, $baz, $quux);
As previously mentioned, there should be a space on both sides of the equal sign. When you have a series of related statements, for readability, you can increase the number of spaces appropriately, such as:
$short = foo ($bar);
$long _variable = foo ($baz);

Functions declaration (Function Declarations)
Parameters that contain default values should be placed at the end, and when the function has a return value, try to return the value that is easy to understand:

Copy Code code 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)
When you call a class constructor with no arguments, always include parentheses
$foo = new myClassName ();

Class Builder with parameters
$foo = new myClassName ($arg 1, $arg 2);
If you use a variable as the class name, you must assign a value to the variable before calling the Class Builder:

Copy Code code as follows:

$bar = ' myClassName ';
$foo = new $bar ();
$foo = new $bar ($arg 1, $arg 2);

Arrays (Array)
The values of the array should be separated by a space, and the assignment action symbol (=>) should also contain spaces:
$some _array = array (' Hello ', ' World ', ' foo ' => ' Bar ');
When declaring an array with a character length of more than 80 characters (usually when you are constructing forms and menus), you should write each element branch, indent:
Copy Code code 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 hand error, but a resolution error that prevents a new element from being added to the end and missing commas. (To some extent, it is a recommended practice to add commas at the end of the last array element, even when submitting code to drupal.org, some code instrumentation script detects a warning because the last element does not add commas.) )

quotation marks (quotes)
Drupal does not have a strong standard for the use of single and double quotes, and it only needs to be consistent in the same module.
Using single quotes is more efficient than double quotes, because parsers do not need to find variables between quotes. Here are two things that use double quotes:
Quotes with variables in the middle, such as "Enclose a single quote in the middle of the quotation mark, and use double quotes to avoid escaping the single quote "He's a good person." Of course, you can also use single quotes, but. The pot parser does not handle this very well, and it looks strange to ' he\ ' a good person. '

string concatenation (string concatenations)
You need to add spaces between the point and the string you want to connect to enhance the readability of the code:
If you are simply connecting a variable, you can use double quotes
When you use a connection assignment (. =), you need to reserve space on both sides of the symbol

Note (Comment)
Comment specification separate on Doxygen and annotation format specification pages

Use Include_once () when introducing code (including code)
, using require_once (), any conditional reference file, in the case of any unconditional reference file. These two statements will ensure that the file is only introduced once.
always start with the point path when code is introduced from the current directory or subdirectory
Include_once./includes/mymodule_formatting.inc
in Drupal 7 and later, using Drupal_root Constants:
Require_once Drupal_root. '/' . Variable_get (' Cache_inc ', ' includes/cache.inc ');
PHP Code Tags
Always use the <?php?> to define the PHP code without using the;??>. This is to follow the Drupal specification while also making it easier for code to be referenced in other systems and platforms.
Since Drupal 4.7, the last?> have been deliberately ignored for the following reasons:
removing it avoids whitespace characters at the end of the file, which can cause the file headers to be sent (header already sent) error, xhtml/ XML validation errors, and other issues
the PHP qualifier at the end of the PHP official description is optional
Php.net itself also removes the qualifier at the end of the file (for example, Prepend.inc)

The

semicolon (semicolons)
PHP language requires that most line endings be followed by semicolons in addition to code blocks. The Drupal code specification also has this requirement and is true for code blocks as well. The following is an example of a single line of code block:
 --YES
 --NO
sample URL (Example URL)
use example.com to represent all sample URLs The
naming convention (naming conventions)
functions and variables (functions and Variables)
functions and variable names should use lowercase letters, and the words are separated by an underscore. Functions should be prefixed with module group/module names to avoid conflicts with different modules. The
persistence variable (persistent Variables)
persistent variable refers to the variable that is obtained and set through the Variable_get ()/variable_set () function, and the variable name should be in lowercase letters , and the words are delimited by using an underscore. Persistent variables should also be prefixed with module group/module names to avoid conflicts with different modules.

Constants (Constants)
Constants always require all uppercase letters, and the words are delimited with an underscore. (including PHP built-in constants TRUE, FALSE, NULL)
Constants defined in a module must always be prefixed with uppercase module names.
After Drupal 8 and after, 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 in PHP expressions, so in conditional judgment and non-literal value??? , you should still use the Define () function

Globals (Global Variables)
When you define a global variable, you should start with an underscore and a module/topic name
Classes (Class)
Class names should be named with the Hump (that is, the first letter of the word)

Methods (functions) and attributes (member variables) in a class should use the hump of the first letter lowercase

When you define access permissions, you use protected instead of private, so that other classes can extend and update methods if necessary. Protected and public functions and variables should not begin with an underscore.
More about object-oriented coding specifications
filename (filename)
All document files should be prefixed with a. txt suffix for Windows users to view. Also, all file names should be capitalized, and the file suffix should be all lowercase.
such as README.txt, INSTALL.txt, TODO.txt, CHANGELOG.txt and so on.

Auxiliary modules and tools
Coder Module: You can follow some of the code specifications, the code review and modify the recommendations
Drupal code Sniffer: Codes Instrumentation Tools
Pareview.sh: Also handles the code spec detection script in the sandbox, almost strictly adheres to all of the above code specifications and gives suggestions for modification.

Related Article

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.