PHP specification
1. Why Coding Specifications
• Coding Specification (code conventions) is especially important for programmers for several reasons:
1. In the life cycle of a software, 80% of the cost is spent on maintenance.
2. Virtually no software is maintained by the initial developer throughout its lifecycle.
3. The coding specification can improve the readability of the software, allowing programmers to understand the new code as quickly and thoroughly as possible.
4. If you publish the source code as a product, you need to verify that it is well packaged and clear, just like any other product that has been built.
2. Overview
• Use four spaces instead of the tab indent.
• Remove the "?>" from the bottom of the php file.
• Each line of the program generally less than 80 characters, out of the section, divided into multiple lines of writing.
• Write only one statement per line, and do not allow multiple phrase sentences to be written in a single line.
• Comments should be added for files and functions.
• Uncomment code should be removed in a timely manner.
• The naming of variables and functions should be standardized.
3. Editor settings
3.1. Indent
All indents use spaces instead of tab tabs. PHP files are indented in 4 spaces, HTML files and JavaScript code embedded in HTML files are indented with 2 spaces, and individual JavaScript and CSS files are indented in 4 spaces.
3.2. Character encoding
All PHP, HTML files are saved as no Bom UTF-8 character encoding.
4. Code layout
4.1. Bottom of File
Remove the "?>" at the bottom of the file.
4.2. You must add a blank line after the relative independent program block, variable description
Example: The following example does not conform to the specification
Copy the Code code as follows:
if (! $valid _ni ()) {
...//program code
}
$REPSSN _ind = $ssn _data[' index ']->repssn_index;
$REPSSN _ni = $ssn _data[' index ']->ni;
Should be written as follows:
if (!valid_ni () {
...//program code
}
$REPSSN _ind = $ssn _data[' index]->repssn_index;
$REPSSN _ni = $ssn _data[index]->ni;
4.3. Longer statements are divided into multiple lines of writing
Less than 80 characters for one line of program
Long statements are divided into multiple lines of writing, long expressions to the lower priority operators to divide the new line, the operator placed in the first line of new lines, the division of the new line to be properly indented, so that the layout is neat, the statement is readable.
If there is a long expression or statement in the loop, judgment, etc., then we need to adapt the division, the long expression to divide the new line at the lower priority operator, the operator is placed in the first example of the new line:
Copy the Code code as follows:
$perm _count_msg->len = No7_to_stat_perm_count_len
+ Stat_size_per_fram * strlen ($len);
$act _task_table[$frame _id * stat_task_check_number + $index]->occupied
= $stat _poi[index]->occupied;
$act _task_table[taskno]->duration_true_or_false
= Sys_get_sccp_statistic_state ($stat _item);
if (($taskno < $max _act_task_number)
&& (N7stat_stat_item_valid ($stat _item))) {
...//program code
}
for ($i = 0, $j = 0; ($i < $bufferKeyword [' Word_index ']->word_length)
&& ($j < new_keyword->word_length); $i + +, $j + +) {
...//program code
}
4.4. Write only one statement in a row
Multiple phrase sentences are not allowed to be written in one line, i.e. a single statement is written on a line. Example: The following example does not conform to the specification
$rect->length = 0; $rect->width = 0;
Should be written as follows:
$rect->length = 0; $rect->width = 0;4.5. Always include curly braces
This is another case of being lazy enough to knock two characters and give the code a clear problem.
Example: The following example does not conform to the specification
Copy the Code code as follows:
if ($condition) Do_stuff ();
if ($condition)
Do_stuff ();
while ($condition)
Do_stuff ();
for ($i = 0; $i < $size; $i + +)
Do_stuff ($i);
Should be written as follows
Copy the Code code as follows:
if (condition) {
Do_stuff ();
}
while ($condition) {
Do_stuff ();
}
for ($i = 0; $i < $size; $i + +) {
Do_stuff ();
}
4.6. Switch notation
Example: The following example conforms to the specification
Copy the Code code as follows:
Switch () {
Case ' 1 ':
.. Program
Break
Case ' 2 ':
.. Program
Break
}
4.7. Where are the curly braces placed?
The delimiter of the block (curly braces ' {' and '} ') should be exclusive for each row and be in the same column, and aligned to the left of the statement that references them.
In the beginning of the function body, the definition of the class, and the closing brace in the If, for, do, while, switch, and case statements should be placed at the end of the line, and the opening brace should be in the same column as the beginning of the row where the closing brace is located
Example: The following example does not conform to the specification
Copy the Code code as follows:
For (...)
{
...//program code
}
if (...)
{
...//program code
}
function Example_fun ()
{
...//program code
}
You should write as follows: for (...) {
...//program code
}
if (...) {
...//program code
}
function Example_fun () {
...//program code
}
4.8. Use spaces between symbols
This loosely written code is designed to make the code clearer.
Because the clarity generated by the spaces is relative, there is no need to leave spaces in the already very clear statement, and if the statement is clear enough, the inside of the brackets (that is, the opening parenthesis and the right parenthesis) do not require a space, and no spaces between the braces. In a long statement, if you need to add a lot of space, then you should keep the overall clear, and in the local without space. Do not leave more than two spaces in a row when you leave the operator blank.
Example: The following example does not conform to the specification
Copy the Code code as follows:
$i = 0;
if ($i <7) ...
if (($i < 7) && ($j > 8)) ...
for ($i =0; $i < $size; $i + +) ...
$i = ($j < $size)? 0:1;
Do_stuff ($i, "foo", $b);
Should be written as follows:
Copy the Code code as follows:
$i = 0;
if ($i < 7) ...
if (($i < 7) && ($j > 8)) ...
for ($i = 0; $i < $size; $i + +) ...
$i = ($j < $size)? 0:1;
Do_stuff ($i, "foo", $b);
4.9. String connector
When you use a string connector, you must add spaces to both sides of the period (.).
Example: The following example does not conform to the specification
Copy the Code code as follows:
$str = ";
$str = ";
Should be written as follows: $str = ';
4.10. Use of Blank lines
No one wants to see a bunch of disorderly code crowding in. When we write code, we always use some blank lines to add code readability. Reasonable use of whitespace to differentiate code snippets makes the logic of the code more explicit. The following two conditions are imposed on the empty line we impose:
• must have only 1 empty lines before?>
• There must be 1 blank lines between the two functions.
return, die, exit should be preceded by a blank line if there are other statements.
We don't allow extra spaces at the end of the line in the code.
5. Notes
5.1. File Header Template
/**
* Shopex Online Store file Chinese name
* Description of the class or file, where you can use HTML
*
* @package
* @version $Id $
* @copyright 2003-2008 Shanghai ShopEx Network Tech. Co., Ltd.
* @license Commercial
* =================================================================
*/
5.2. function Header Comment
Each function should have a comment before it, telling a programmer what it needs to know to use the function. A minimized comment should include: The meaning of each parameter, the expected input, the output of the function. The comment should also give the behavior of the function under the error condition (and what the error condition is). (note should ensure that) other people do not have to look at the code of this function, they can confidently call this function in their own code.
In addition, adding comments to any tricky, obscure, or not obvious code is certainly something we should do. What is especially important to a document is any assumptions your code makes, or the premise that it works correctly. Any developer should be able to view any part of the application and determine, within a reasonable time, what is going on (in the execution of the code).
Copy the Code code as follows:
/**
* Some_func
* Description of function meaning
* This section is free to enter HTML
* Because this is Phpdocument's agreement.
*
* @param mixed $arg 1 Description of parameter one
* Description of @param mixed $arg 2 parameter II
* @access Public
* @return BOOL
*/
5.3. Delete the repealed comment
Uncomment, comment code to be deleted in time
5.4. Constants and annotations
For all variables and constants that have a physical meaning, if their names are not fully self-explanatory, they must be annotated at the time of Declaration, explaining their physical meaning. The comments for variables, constants, and macros should be placed either adjacent to or to the right.
Example:
Copy the Code code as follows:
Active statistic Task number
Define (' Max_act_task_number ', 1000)
Define (' max_act_task_number ', +);//Active statistic TASK number
5.5. Comment Location
Comments should be similar to the code they describe, and the comments on the code should be placed either above or to the right (comments on a single statement) adjacent to each other, not below, as shown above, separated from the code above with a blank line.
Example: The following example does not conform to the specification
Example 1:
copy code code is as follows:
//Get Replicate Sub System index and net indicator
$repssn _ind = $ssn _data[$index]->repssn_index;
$REPSSN _ni = $ssn _data[$index]->ni;
Example 2: $repssn _ind = $ssn _data[$index]->repssn_index;
$repssn _ni = $ssn _data[$index]->ni;
//Get Replicate Sub system index and net indicator
should be written as follows
//Get Replicate Sub system index and net INDICATOR
$REPSSN _ind = $ssn _data[$index]->repssn_index;
$repssn _ni = $ssn _data[$index]->ni;
5.6. Data structure Declaration annotated
Data Structure Declaration (array), which must be commented. Comments on the data structure should be placed on top of each other, not below, and comments on each field in the structure are placed to the right of the field.
Example: Description as follows
Copy the Code code as follows:
SCCP interface with SCCP user primitive message name
$SCCP _user_primitive = Array (
' N_unitdata_ind ' = 1,//SCCP notify SCCP user unit data come
' N_notice_ind = 2,//SCCP notify user The No.7 network can not transmission this message
N_unitdata_req = 3//SCCP user's unit data transmission request
)
5.7. Global variable annotations
A global variable should have a more detailed comment, including a description of its function, range of values, which functions or procedures to access it, and considerations for access.
5.8. Note Indentation
Annotations are indented in the same way as described, allowing the program to be formatted neatly and easily read and understood.
Example: The following example does not conform to the specification
Copy the Code code as follows:
function Example_fun () {
Code One comments
Codeblock One
Code comments
Codeblock
}
Should be changed to the following layout:
Copy the Code code as follows:
function Example_fun () {
Fdgfd
Codeblock One
Code comments
Codeblock
}
5.9. Separate the comment from the code above with a blank line
Example: The following example shows that the code is too compact.
Copy the Code code as follows:
Code One comments
Program Code One
Code comments
Program code
Should be written as follows//code one comments
Program Code One
Code comments
Program code
5.10. Continuous Case comments
For a case statement under a switch statement, if the next case is processed after a case has to be processed because of a particular situation, it must be preceded by an explicit comment before the cases statement finishes processing. This makes it clearer what the program writer intends to do to prevent the omission of the break statement without reason.
Example:
Copy the Code code as follows:
Switch ($i) {
Case ' Cmd_init ':
echo "I equals 0";
Break
Case ' Cmd_start:
echo "I equals 1";//Now jump to case cmd_a
Case ' cmb_a ':
echo "I equals 2";
Break
}
5.11. Structure declaration
The array variable representing the struct in the code is declared in advance.
Example:
Copy the Code code as follows:
function Example_fun () {
$student = Array (
' Name ' = ' xiaoming ',//Name
' Addr ' = ' Detailed address ',//Address
' Sex ' = ' male ',//gender
' City ' = ' Shanghai '//Cities
)
}
5.12. Comment Format
Note format is uniform, single-line comments must use "//... ", multiple lines using a pair of/*...*/
Example: The following example does not conform to the specification.
Copy the Code code as follows:
/* If Receive_flag is TRUE */
/* If Receive_flag is FALSE */
if ($receive _flag)
Should be written as follows:
Copy the Code code as follows:
/* If Receive_flag is TRUE
If Receive_flag is FALSE */
if ($receive _flag)
5.13. Comments are mainly in Chinese
Notes should take into account the procedural legibility and appearance of the factors, the use of the language if both Chinese and English, it is recommended to use more Mandarin, unless it can be expressed in a very fluent and accurate English.
6. Naming provisions
6.1. Prohibition of pinyin nomenclature
Phonetic nomenclature is forbidden in the code.
6.2. Variable naming
Variable names should all be lowercase, and the words separated by a single underscore.
For example: $current _user is correct, but $currentuser and $currentUser are not correct.
The name should be descriptive and concise. We naturally don't want to use lengthy sentences as variable names, but it's better to enter a few characters than to wonder what a variable is for.
6.3. Function naming
Use a lowercase name separated by a single underscore between words, allowing the verb phrase to name the function that performs the action. If it is an OOP method, you can only have verbs (nouns are the object itself). Allows the table function to be named.
Example:
Copy the Code code as follows:
function Print_record ($rec _ind)
function Input_record ()
function Get_current_color ()
function Is_boy ()
Verb table: add/edit/remove begin/end Create/destroy
First/last Get/release Get/set
Increment/decrement Put/get
Lock/unlock Open/close
Min/max old/new Start/stop
Next/previous Source/target Show/hide
Send/receive
Cut/paste Up/down
Copula table: IS have
For private methods, start with _.
6.4. Cycle counter
The only case where a single character variable name is allowed is when it is used as a loop counter. In this case, the counter of the outer loop should always be $i. If there is a loop inside the loop, its counter should be $j, then $k, and so on. This specification does not apply if the counter of the loop is a variable that already exists and has a meaningful name.
For example:
Copy the Code code as follows:
for ($i = 0; $i < $outer _size; $i + +) {
for ($j = 0; $j < $inner _size; $j + +) {
Foo ($i, $j);
}
}
6.5. Function parameters
Parameters follow the same conventions as variable names. We don't want a bunch of these functions: Do_stuff ($a, $b, $c). In most cases, we want to just look at the declaration of a function and know how to use it.
7. Readability
7.1. Precedence of Operators
Note the precedence of the operators, and use parentheses to clarify the order in which the expressions are manipulated, and to avoid using the default precedence. Prevent misunderstandings in reading programs and prevent program errors due to default prioritization and design ideas.
Example: Expressions in the following statements
Copy the Code code as follows:
$word = ($high << 8) | $low (1)
if ($a | $b) && ($a & $c)) (2)
if ($a | $b) < ($c & $d)) (3)
If written as $high << 8 | $low
$a | $b && $a & $c
$a | $b < $c & $d
Due to $high << 8 | $low = ($high << 8) | $low,
$a | $b && $a & $c = ($a | $b) && ($a & $c),
(1) (2) No error, but the statement is not easy to understand; $a | $b < $c & $d = $a | ($b < $c) & $d,
(3) cause the judgment condition error.
7.2. Avoid numbers, use constants
Avoid the use of hard-to-understand numbers and replace them with meaningful represented.
Example: The program below has poor readability.
Copy the Code code as follows:
if ($trunk [$index]->trunk_state = = 0) {
$trunk [$index]->trunk_state = 1;
...//program code
}
Should be changed to the following form.
Copy the Code code as follows:
Define (trunk_idle, 0)
Define (TRUNK_BUSY, 1)
if ($trunk [$index]->trunk_state = = Trunk_idle) {
$trunk [$index]->trunk_state = trunk_busy;
...//program code
}
7.3. The more closely related code in the source program should be as contiguous as possible
Easy to read and find programs.
Example: The following code layout is not reasonable.
Copy the Code code as follows:
$rect->length = 10;
$char _poi = $str;
$rect->width = 5;
It may be clearer if you write as follows.
Copy the Code code as follows:
$rect->length = 10;
$rect->width = 5; The length and width of the rectangle are more closely related and put together.
$char _poi = $str;
8. Functions
8.1. Validity check of interface function parameters
The validity check of the function parameter should be the responsibility of the caller of the function, and the interface function should check the necessity legality (not mandatory).
Summarized as: Outside the main, within a supplement, internal not mandatory.
8.2. Function size
The size of the function is limited to 100 lines, excluding comments and space lines.
8.3. One function only completes one function
8.4. Do not design multi-purpose functions
In addition to the scheduling function, multi-function set in a function, it is likely to make the function of understanding, testing, maintenance and so difficult
8.5. Multi-segment code repeat the same thing
If multiple pieces of code do the same thing over and over again, there may be a problem with the partitioning of the function. If there is a substantial association between the statements of this code and the same function is done, consider constructing this code into a new function.
9. Quality Assurance
9.1. Compatibility
9.2. Ternary operators
Ternary operator, in one line of code only allowed to use the first level
The ternary operator should only be used to do simple things. They are only suitable for assignment and are not used for function calls or any complex things. If used improperly, they can affect readability, so don't indulge in using them to reduce typing.
Example: where they should not be used
(($i < $size) && ($j > $size))? Do_stuff ($foo): Do_stuff ($bar);
Example: Where are the appropriate places to use them $min = ($i < $j)? $i: $j;
9.3. Initializing variables
Variables should be initialized before they are used, and error_reporting will join E_notice. This means that the uninitialized variable will be an error. This problem is most likely to occur when checking what variables are passed in the HTML form. These errors can be avoided by using the inline isset () or the empty () function to check if a variable is set.
Example: Old Fashioned
if ($forum) ...
New approach: if (!empty ($forum)) ...
if (Isset ($forum)) ...
9.4. Referencing strings
There are two different ways to reference strings in PHP-using single quotes or double quotes. The main difference is that the parser performs a variable substitution in a string enclosed in double quotation marks, but not in a string enclosed in single quotation marks. Therefore, you should always use single quotes, unless you do need to replace the string with a variable. In this way, we can avoid having the parser parse a bunch of strings that do not need to be replaced. Similarly, if you use a string variable as part of a function call, you do not need to enclose that variable in quotation marks. Again, that will only add unnecessary work to the parser. In any case, note that almost all escape sequences in double quotes do not work in single quotes. If this specification makes your code difficult to read, be careful and break it with confidence.
Example: The following example does not conform to the specification
Copy the Code code as follows:
$str = "A really long string with no variables for the parser to find.";
Do_stuff ("$str");
Should be written as follows:
Copy the Code code as follows:
$str = ' This was a really long string with no variables for the parser to find. ';
Do_stuff ($STR);
When you have to use double quotes as a reference for readability reasons, be aware that all of the variables need to be surrounded by {}: $str = "This is ' {$what} ' with no variables for the parser to find."
9.5. Key names for associative arrays
In PHP, it is possible to use a string that is not enclosed in quotation marks as the key name for an associative array. We don't want to do this--in order to avoid confusion, the string should be enclosed in quotation marks. Note that this is only the case when we use the string, not when we use the variable. Example: The following example does not conform to the specification
$foo = $assoc _array[blah];
Should be written as follows:
$foo = $assoc _array[' blah ');
9.6. Simplifying operators
The simplified auto-increment ($i + +) and the subtract ($i-) operators are the only simplified operators that cause readability problems. These operators should not be used as part of an expression. However, they can be used exclusively on a single line. Using them in expressions (with convenience) is not enough to debug headaches (at the cost).
Example: The following example does not conform to the specification
Copy the Code code as follows:
$array [+ + $i] = $j;
$array [$i + +] = $k;
Should be written as follows: $i + +;
$array [$i] = $j;
$array [$i] = $k;
$i + +;
9.7. If and else if
When there are multiple conditions in a conditional statement, and there is a judgment of the value of the variable, it is necessary to put the judgment statement of the variable before other conditional statements.
Example: The following example does not conform to the specification
Copy the Code code as follows:
if (function_exists (' Ob_gzhandler ') && $val = = 1) {
}
Should be written as follows: if ($val = = 1 && function_exists (' Ob_gzhandler ')) {
}
While the else if and ElseIf functions in PHP are essentially the same. But for the sake of the unity of the code (there is also the rumor that else if there is an unstable situation), we require that the space between ElseIf not be preserved: if ($bool = = 2) {
}elseif ($n = 1) {
}
9.8. Initialization of input variables
Whether it is a function parameter or a variable passed through a URL, it must be preprocessed before the call and set the default value.
The string must be processed with trim and escape, and if the value of the variable is within the range we expect, the illegal value of the variable needs to be treated accordingly, and for a numeric type variable it needs to be intval or floatval.
9.9. Require and include
We require the use of require_once or include_once when using the include file in the program, and we do not allow the use of require or include.
Only require_once can be used for files that the program must contain, and only include_once is used for certain conditionally contained files when referenced.
9.10. File naming
The filenames should all be lowercase, and the words should be separated by a single underscore.
For example: current_user.php is correct, but currentuser.php and currentuser.php are not correct.
The name should be descriptive and concise. We naturally don't want to use lengthy sentences as file names, but it's better to enter a few characters than to wonder what a file is for.
Ten. SQL syntax
10.1. SQL Code Layout
Now that we're all using different editor settings, don't try to do things like implementing column alignment in SQL code. The way to do this is to break the statements to their individual lines, regardless of the method. Here's an example of what the SQL code should look like. Notice where to break the sentence, capitalize, and use parentheses.
For example:
Copy the Code code as follows:
SELECT field1 as something, Field2, field3
From ' table ' A, ' table ' B
WHERE (this = that) and (This2 = THAT2)
10.2. Table name and field values
The table name and field name in the SQL statement avoid the use of reserved words, and the variable names for all field values, if they are numeric, require coercion of type conversions. Intval,floatval ...
10.3. SQL SELECT statement
The following code is not allowed for fields that are known to be queried:
SELECT * from ' mytable '
Instead, write each field name and don't be lazy. SELECT col1, col2, col3 from ' mytable '
If you need to get the number of known records, use limit offset, count, and try not to use the No Limit SELECT statement.
Use select count ([*|col1]) from, and try not to use the Select col1 from method, if you need or satisfy the number of records for the condition.
When you need to do logical operations, try not to use not equal, you can use greater than or less than the way.
10.4. SQL INSERT Statements
SQL INSERT statements can be written in two different ways. Or you explicitly indicate the column you want to insert, or you already know the order of the columns in the data, without specifying them in detail. We want to use the previous method, which is to specify which columns to insert. This means that the application code does not depend on the order of the fields in the database, nor does it crash because we add additional fields (unless, of course, they are specified as not NULL).
For example:
# It's not what we want #
Copy the Code code as follows:
INSERT into ' mytable '
VALUES (' Something ', 1, ' Else ')
# that's right.
Copy the Code code as follows:
INSERT into ' mytable ' (Column1, Column2, Column3)
VALUES (' Something ', 1, ' Else ')
Smarty syntax
11.1. The delimiting character
The delimiting character is <{}>
11.2. Double quotes, single quotes
To prevent Dreamweaver from rewriting the double quotation marks in the Smarty statement to ", we require that double quotes be not allowed in the curly braces of the smarty, but single quotes.
The wrong wording:
<{if $user _name eq ""}> Anonymous users <{/if}>
<{insert name= "Query_info"}>
The correct wording:
<{if $user _name eq '}> anonymous users <{/if}>
<{insert name= ' Query_info '}>
11.3. Conditional setting of HTML property values
When you need to conditionally set HTML element property values in a template, we require that all statements be enclosed in double quotation marks. The wrong code:
Copy the Code code as follows:
<{if $promote _price>0}> "Promote_goods"
<{else}> "Normal_goods" <{/if}>
><{$goods .goods_name}>
The correct wording:
Copy the Code code as follows:
Promote_goods
<{else}>nomarl_goods<{/if}> "><{$goods .goods_name}>
11.4. Conditional modifiers
In Smarty, you can use EQ, NEQ, GT, LT, etc. to represent = =,! =, >, <, respectively. So what exactly should we use?
modifiers such as = =,! = are not allowed when the Smarty statement appears inside the HTML tag, and if such modifiers are used, it is possible that the symbol or other HTML-related symbols will be automatically escaped by Dreamweaver.
In short, use such conditional modifiers as EQ, GT, etc. to avoid direct use of = =, >.
http://www.bkjia.com/PHPjc/328171.html www.bkjia.com true http://www.bkjia.com/PHPjc/328171.html techarticle PHP Specification 1. Why coding specification Code conventions is especially important for programmers, for the following reasons: 1. In the life cycle of a software, 80% spends ...