An in-depth discussion of PHP coding specifications _php Tutorial

Source: Internet
Author: User
Tags php language parse error drupal
Indents and whitespace characters (indenting and whitespace)
Use 2 spaces without using the TAB key for code indentation (notepad++, Eclipse and other editors support this configuration);
There should be no whitespace characters at the end of the line
You should use \ n (Unix line break) instead of \ r \ n (Windows line break)
All files should end with a blank line

Operator (Operators)
All two-tuple operators (operators between two values), such as +,-, =,! =, =, >, and so on, need to 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 + +, should not include a space between the value and the operator

Transformation (Casting)
A space, such as an (int) $mynumber, should be added between (type) and the variable to be transformed.
Control structure (structures)
The control structure contains if, for, while, switch, and so on, and here is an example of a simple if statement structure:
Copy CodeThe 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 parenthesis to differentiate it from the function call.
The curly braces should always be used, even if the curly braces are optional. This can enhance the readability of the code and reduce the logic errors caused by nesting.
Switch Statement Structure example:
Copy CodeThe 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 lengths and packages (lines length and wrapping)
Typically, the length of each line of code should not exceed 80 characters
The line length can exceed 80 characters in the following cases: When the line contains too long function name, function/class definition, variable declaration, etc.
For easy reading and comprehension, the length of the control structure can exceed 80 characters.
Copy CodeThe 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 is also acceptable, but should
Always being documented, explaining why a particular check was done.
if (Preg_match (' @ (/|\\) (\.\.| ~) @ ', $target) && Strpos ($target _dir, $repository)
!== 0) {
return FALSE;
}

control conditions (condition) should not write multiple lines
Control conditions should be properly split for readability and comprehension, and the following situations should be avoided when writing code:
Copy CodeThe 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 conditions is not only easy to read, but it also makes it easy to add comments to let people know why such conditions are judged
Copy CodeThe code is as follows:
Key is a 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
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) {
...
}

function call (functions Calls)
When calling a function, there is no space between the function name and the opening parenthesis, except for the last argument, followed by a space after each argument, such as:
$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, for readability reasons, you can increase the number of spaces appropriately, such as:
$short = foo ($bar);
$long _variable = foo ($baz);

Functions declaration (Function Declarations)
The parameters that contain the default values should be placed at the end, and when the function has a return value, try to return a value that is easy to understand:
Copy the Code code as follows:
function Funstuff_system ($field) {
$system ["description"] = t ("This module inserts funny the text into posts randomly.");
return $system [$field];
}

class constructor call (class Constructor Calls)
When a class constructor with no arguments is called, 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 need to assign a value to the variable before calling the class constructor:
Copy CodeThe code is 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 spaces, and the assignment action symbol (= =) should also contain spaces:
$some _array = array (' Hello ', ' World ', ' foo ' = ' bar ');
When declaring an array of characters longer than 80 characters (usually when constructing forms and menus), each element should be written in line, indent:
Copy CodeThe code is as follows:
$form [' title '] = Array (
' #type ' = ' TextField ',
' #title ' and T (' title '),
' #size ' = 60,
' #maxlength ' = 128,
' #description ' and 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 parse error that prevents a new element from being added to the last one because of a missing comma. (In a way, it is a recommended practice to add a comma at the end of the last array element, even when the code is being submitted to drupal.org, some code instrumentation scripts will have a warning prompt because the last element does not have a comma added.) )

quotation marks (Quotes)
Drupal does not have a very strong standard for using single and double quotes, just keeping the usage uniform within the same module.
Using single quotes is more efficient than double quotation marks, because the parser does not need to look for variables between quotes. The following are two cases where double quotes are used:
There are variables in the middle of the quotation marks, such as

$header

"
Enclose quotation marks in the middle, using double quotation marks to avoid escaping the single quote "He's a good person." Of course you can use single quotes, but the. Pot parser doesn't handle this very well and looks weird ' he\ 's a good person. '

String Connection (string concatenations)
need to add a space between the point and the string to be concatenated to enhance code readability:
If you are simply connecting variables, you can use double quotation marks
When using the connection assignment (. =), you need to reserve a space on both sides of the symbol

Comment (Comment)
Comment specifications are discussed separately on the Doxygen and Comment format Specification page

With the introduction of code (including code)
any unconditional reference to the file, using require_once (), any conditional reference to the file, use Include_once (). These two statements guarantee that the file will only be introduced once.
When you introduce code from the current directory or subdirectory, always start with a point path
include_once./includes/mymodule_formatting.inc
in Drupal 7 and later, use Drupal_root Constant:
require_once drupal_root. '/' . Variable_get (' Cache_inc ', ' includes/cache.inc ');
PHP Code Tags
Always use the!--? php?--to define PHP code without using the!--??--. This is to follow the Drupal specification and also facilitates the 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 "header already sent" error, xhtml/ XML validation errors, and other issues
PHP qualifier at the end of the official description of the web is optional
Php.net itself removes the delimiter at the end of the file (such as Prepend.inc)

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

Constants (Constants)
Constants always require all uppercase letters, and the words are delimited with underscores. (includes PHP built-in constants TRUE, FALSE, NULL)
Constants defined in the module must always be prefixed with the uppercase module name.
In Drupal 8 and beyond, you should use the Const keyword instead of the define () function to define constants, because they are more efficient
Note that const cannot be used in PHP expressions, so in conditional and non-literal denominations (non-literal value??? ), you should still use the Define () function

Global variables (Globals Variables)
When defining global variables, you should start with an underscore and a module/subject name
Classes (Class)
The class name should be named with a camel (that is, capitalize the first letter of the word)

Methods (functions) and properties (member variables) in a class should use the first lowercase camel-

When defining access permissions, use protected instead of private, so that other classes can extend and update methods when necessary. The 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 appended with the. txt suffix for easy viewing by Windows users. Also, all file names should be capitalized, and the file suffixes should all be 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, the code to review and modify the recommendations
Drupal code Sniffer: Codes Specification Detection Tool
PAREVIEW.SH: Also handles code spec detection scripts in the sandbox, almost strictly complying with all of the code specifications above and proposing modifications.

http://www.bkjia.com/PHPjc/327453.html www.bkjia.com true http://www.bkjia.com/PHPjc/327453.html techarticle indentation and white-space characters (indenting and whitespace) use 2 spaces without the TAB key for code indentation (notepad++, Eclipse and other editors support this configuration); The end of the line should not be ...

  • 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.