An indispensable standard for beginners of JoshChen_php

Source: Internet
Author: User
Tags coding standards
So today, I have sorted out the PHP specifications for your reference. As the saying goes, "the rules are dead and people are living .". Yes, but people who grow up in rules will have a bunch of very enviable good habits. PHP specifications
1. Why coding standards?
• Code conventions is especially important for programmers for the following reasons:
1. in a software life cycle, 80% of the cost is used for maintenance.

2. almost no software is maintained by the original developer throughout its lifecycle.

3. coding specifications can improve the readability of software and allow programmers to fully understand new code as soon as possible.

4. if the source code is released as a product, check whether it is well packaged and clear, just like any other product that has been built.

2. Summary
• Use four spaces to replace tab indentation.
• Remove "?>" at the bottom of the PHP file ".
• Each line of programs is generally less than 80 characters. the excess part is divided into multiple lines of books.
• Only one statement can be written in each row, and multiple phrase sentences cannot be written in one row.
• Add comments to files and functions.
• Abolished comments should be deleted in a timely manner.
• The names of variables and functions should be standardized.

3. editor settings
3.1. indent
All indentions replace tabs with spaces. The PHP file uses four spaces for indentation. the HTML file and the Javascript code embedded in the HTML file use two spaces for indentation. the separate Javascript and CSS files use four spaces for indentation.

3.2. Character encoding
All PHP and HTML files are saved as the character encoding of the No Bom UTF-8.

4. code layout
4.1. bottom of the file
Remove "?>" at the bottom of the file ".

4.2. empty lines must be added between relatively independent program blocks and variable descriptions
Example: The following example is invalid.

The code is as follows:


If (! $ Valid_ni ()){
... // Program code
}
$ Repssn_ind = $ ssn_data ['index']-> repssn_index;
$ Repssn_ni = $ ssn_data ['index']-> ni;
It 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. long statements should be written into multiple lines of books
A program must contain less than 80 characters

A long statement should be divided into multiple lines of writing. a long expression should divide a new line at the lower-priority operator, and the operator should be placed at the beginning of the new line. The new line should be properly indented to make the layout neat, the statement is readable.

If a long expression or statement exists in a statement such as loop or judgment, the adaptive division is required. a long expression must divide a new line at the lower-priority operator, and the operator is placed at the first of the new line. example:

The code is 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 one row
Multiple phrase sentences cannot be written in one row, that is, only one statement can be written in one row. Example: The following example is invalid.

$ Rect-> length = 0; $ rect-> width = 0;
It should be written as follows:
$ Rect-> length = 0; $ rect-> width = 0; 4.5. always contains braces
This is another situation that causes the code to be clear because you are too lazy to double characters.

Example: The following example is invalid.

The code is 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

The code is as follows:


If (condition ){
Do_stuff ();
}
While ($ condition ){
Do_stuff ();
}
For ($ I = 0; $ I <$ size; $ I ++ ){
Do_stuff ();
}


4.6 switch statement
Example:

The code is as follows:


Switch (){
Case '1 ':
.. Program
Break;
Case '2 ':
.. Program
Break;
}


4.7. where are braces?
The program block delimiters (braces '{' and '}') should each have an exclusive row in the same column and be left aligned with the statements that reference them.

The right braces in the beginning of the function body, the definition of the class, and if, for, do, while, switch, and case statements should be placed at the end of the row, the left braces should be in the same column as the first row of the right braces.

Example: The following example is invalid.

The code is as follows:


For (...)
{
... // Program code
}

If (...)
{
... // Program code
}

Function example_fun ()
{
... // Program code
}
Should be written as follows: (...){
... // Program code
}

If (...){
... // Program code
}

Function example_fun (){
... // Program code
}


4.8. use spaces between symbols
The purpose of writing code in this loose way is to make the code clearer.

Since the clarity produced by leaving spaces is relative, there is no need to leave spaces in statements that are already very clear, if the statement is clear enough, no space is required for the inside of the brackets (that is, the front of the left and right brackets), and no space is required for the multiple parentheses. In a long statement, if you need to add a lot of spaces, you should keep the overall clarity, without spaces. Do not leave more than two consecutive spaces for the operator.

Example: The following example is invalid.

The code is as follows:


$ I = 0;
If ($ I <7 )...
If ($ I <7) & ($ j> 8 ))...
For ($ I = 0; $ I <$ size; $ I ++ )...
$ I = ($ j <$ size )? ;
Do_stuff ($ I, "foo", $ B );


It should be written as follows:

The code is 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 a string connector is used, spaces must be added on both sides of the period.

Example: The following example is invalid.

The code is as follows:


$ Str = '';
$ Str = '';
It should be written as follows: $ str = '';


4.10. use of empty rows
No one wants to see a bunch of unordered code. When writing code, we always use some blank lines to increase code readability. The rational use of spaces to differentiate code segments makes the logic of the code clearer. We forcibly stipulate the following two cases of empty rows:

• •?> There must be only one blank line before
• There must be one empty row between two functions.
• If there are other statements before return, die, and exit, an empty line should be added.
In the code, we do not allow extra spaces at the end of the line.

5. Notes
5.1. file header template
/**
* Chinese name of ShopEx online store files
* Class or file description. here, you can use html
*
* @ Package
* @ Version $ Id $
* @ Copyright 2003-2008 Shanghai ShopEx Network Tech. Co., Ltd.
* @ License Commercial
* ===================================================== ======================================
*/
5.2. function header comments
Every function should be annotated before, telling a programmer what to know when using this function. A minimal comment should include the meaning of each parameter, the expected input, and the output of the function. The comments should also show the behavior of the function under the error condition (and the specific error condition. (Note should ensure) others can confidently call this function in their own code without having to look at the code of this function.

In addition, adding comments to any tricky, obscure, or non-obvious code is definitely what we should do. What is especially important to the document is any assumptions made by your code, or the premise that it runs correctly. Any developer should be able to view any part of the application and determine, within a reasonable period of time, what happened (in code execution.

The code is as follows:


/**
* Some_func
* Function description
*

This part can be entered at willHtml


* This is the phpdocument convention.
*
* @ Param mixed $ arg1 parameter 1
* @ Param mixed $ arg2 parameter 2 description
* @ Access public
* @ Return bool
*/


5.3. delete abolished comments
Abolished comments. the comments must be deleted in a timely manner.

5.4. add comments to constants
For all variables and constants with physical meanings, if their names are not fully self-annotated, they must be annotated during declaration to describe their physical meanings. Comments of variables, constants, and macros should be placed in adjacent positions or the right side above them.

Example:

The code is as follows:


// Active statistic task number
Define ('max _ ACT_TASK_NUMBER ', 1000)

Define ('max _ ACT_TASK_NUMBER ', 1000); // active statistic task number


5.5. comment position
The comment should be similar to the code described in it. the comment on the code should be placed above it or the right side (the comment on a single statement) adjacent location, and should not be placed below, if it is placed above, it should be separated by blank lines with the above code.

Example: The following example is invalid.

Example 1:

The 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. add comments to the data structure declaration
The data structure Declaration (array) must be annotated. The comment on the data structure should be placed in the adjacent position above it and cannot be placed below; the comment on each field in the structure should be placed on the right side of this field.

Example:

The code is 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 required Y 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 comments
Global variables should be annotated in detail, including descriptions of their functions, value ranges, which functions or processes access them, and precautions for access.

5.8. comment contraction
The comment is scaled in the same way as the description, so that the program can be neatly formatted and easy to read and understand.

Example: The following example is invalid.

The code is as follows:


Function example_fun (){
// Code one comments
CodeBlock One

// Code two comments
CodeBlock Two
}


The layout should be changed to the following layout:

The code is as follows:


Function example_fun (){
// Fdgfd
CodeBlock One

// Code two comments
CodeBlock Two
}


5.9. separate comments from the code above with blank lines
Example: The following example shows that the code is too compact.

The code is as follows:


// Code one comments
Program code one
// Code two comments
Program code two
It should be written as follows // code one comments
Program code one

// Code two comments
Program code two


5.10. continuous case comments
If a case statement under a switch statement needs to be processed in the next case after a case is processed in special cases, a clear comment must be added before the case statement is processed and the next case statement. In this way, the intention of the program writer is clear, and the break statement is effectively prevented from being omitted for no reason.

Example:

The code is as follows:


Switch ($ I ){
Case 'command _ init ':
Echo "I equals 0 ";
Break;
Case 'command _ START:
Echo "I equals 1"; // now jump into case when _a
Case 'cmb _ ':
Echo "I equals 2 ";
Break;
}


5.11. struct declaration
The array variables in the code that represent the struct must be declared in advance.

Example:

The code is as follows:


Function example_fun (){
$ Student = array (
'Name' => 'xiaoming ', // name
'Addr '=> 'detailed address', // address
'Sex' => 'male', // gender
'City' => 'Shanghai' // city
)
}


5.12. comment format
The comment format is uniform, and the single-line comment must use "//…… ", Use one/*… for multiple rows /*... */

Example: The following example is invalid.

The code is as follows:


/* If receive_flag is TRUE */
/* If receive_flag is FALSE */
If ($ receive_flag)


It should be written as follows:

The code is as follows:


/* If receive_flag is TRUE
If receive_flag is FALSE */
If ($ receive_flag)


5.13. the notes are mainly in Chinese.
Note should take into account the ease of reading and appearance of the program layout. if the language is Chinese or English, it is recommended to use more Chinese unless it can be expressed in fluent and accurate English.

6. naming rules
6.1. the pinyin naming method is forbidden.
Do not use the pinyin naming method in the code.

6.2. variable naming
Variable names should all be in lower case, and words are separated by a single underline.

For example, $ current_user is correct, but $ currentuser and $ currentUser are incorrect.

The name should be descriptive and concise. We naturally do not want to use lengthy sentences as variable names, but it is better to enter a few characters to wonder what a variable is.

6.3. function name
Lowercase names separated by single underscores (_) are used to name a function that executes an operation. For the OOP method, only the verb can be used (the noun is the object itself ). Allows the name of the system Table function.

Example:

The code is 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

Vocabulary: is has
For private methods, start.

6.4. cyclic counter
The only scenario where a single-character variable name is allowed is when it acts as a loop counter. In this case, the counter of the outer loop should always be $ I. If a loop is inside the loop, its counter should be $ j, but $ k, and so on. If the counter of a loop is a variable with a valid name, this specification does not apply.

For example:

The code is 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 such functions: do_stuff ($ a, $ B, $ c ). In most cases, we want to know how to use the function just by looking at the declaration of the function.

7. readability
7.1. operator priority
Pay attention to the operator priority, and use parentheses to specify the Operation Order of the expression to avoid using the default priority. Avoid misunderstanding when reading the program, and prevent program errors because the default priority is inconsistent with the design philosophy.

Example: expression in the following statement

The code is as follows:


$ Word = ($ high <8) | $ low (1)
If ($ a | $ B) & ($ a & $ c) (2)
If ($ a | $ B) <($ c & $ d) (3)
For $ high <8 | $ low
$ A | $ B & $ a & $ c
$ A | $ B <$ c & $ d
Because $ 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) an error occurred while determining the conditions.

7.2. avoid numbers and use constants
Avoid using numbers that are hard to understand and replace them with meaningful constants.

Example: The following program has poor readability.

The code is as follows:


If ($ trunk [$ index]-> trunk_state = 0 ){
$ Trunk [$ index]-> trunk_state = 1;
... // Program code
}


The format should be changed to the following.

The code is 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. code closely related to the source program should be as adjacent as possible
It facilitates program reading and searching.

Example: the following code layout is not reasonable.

The code is as follows:


$ Rect-> length = 10;
$ Char_poi = $ str;
$ Rect-> width = 5;


It may be clearer if it is written as follows.

The code is as follows:


$ Rect-> length = 10;
$ Rect-> width = 5; // The length and width of the rectangle are closely related and put together.
$ Char_poi = $ str;

8. Functions
8.1. check the validity of interface function parameters
The caller of the function is responsible for checking the validity of function parameters. The Interface function checks the validity of required parameters (not mandatory ).

The conclusion is as follows: it is mainly external, supplemented by internal, and not mandatory.

8.2. function scale
The number of functions is limited to 100 rows, excluding comments and space rows.

8.3. one function completes only one function
8.4. do not design all-purpose functions
In addition to scheduling functions, functions that integrate multiple functions may make it difficult to understand, test, and maintain functions.

8.5. multiple pieces of code repeat the same thing
If multiple sections of code repeat the same task, there may be problems with function division. If the statements in this code segment are substantially associated with each other and complete the same feature, you can consider constructing this code segment into a new function.

9. Quality Assurance
9.1. compatibility
9.2. ternary operators
Ternary operators. only one level can be used in one line of code.

The ternary operator should only be used for simple operations. They are only suitable for assignment, and are not used for function calls or any complicated tasks. Improper use affects readability, so do not 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 to use them $ min = ($ I <$ j )? $ I: $ j;

9.3. initialize the variable
The variable should be initialized before use, and error_reporting will be added to E_NOTICE. This means that an error is returned if the variable is not initialized. This problem is most likely to occur when you check what variables are passed in the HTML form. These errors can be avoided by using the embedded isset () or empty () function to check whether a variable is set.

Example: Old method
If ($ forum )...
New method: if (! Empty ($ forum ))...
If (isset ($ forum ))...

9.4. reference string
There are two different ways to reference strings in PHP-using single quotes or double quotes. The main difference is that the parser performs variable replacement in the string enclosed by double quotation marks, but not in the string enclosed by single quotation marks. Therefore, you should always use single quotes unless you do need to replace the variable in the string. In this way, we can avoid the trouble of making 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. Similarly, it only adds 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 hard to read, be careful and rest assured to break it.

Example: The following example is invalid.

The code is as follows:


$ Str = "This is a really long string with no variables for the parser to find .";
Do_stuff ("$ str ");


It should be written as follows:

The code is as follows:


$ Str = 'This is a really long string with no variables for the parser to find .';
Do_stuff ($ str );


When you have to use double quotation marks as a quote because of readability, note that all the variables must be surrounded: $ str = "This is '{$ what}' with no variables for the parser to find."

9.5. key name of the associated array
In PHP, a string without quotation marks can be used as the key name of an associated array. We don't want to do this-to avoid confusion, this string should be enclosed in quotation marks. Note: this is only the case when we use strings, not when we use variables. Example: The following example is invalid.

$ Foo = $ assoc_array [blah];
It should be written as follows:
$ Foo = $ assoc_array ['blah'];

9.6. simplified operators
Simplified auto-increment ($ I ++) and auto-increment ($ 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 exclusively use one row. Using them in expressions is not enough (cost) for debugging ).

Example: The following example is invalid.

The code is as follows:


$ Array [++ $ I] = $ j;
$ Array [$ I ++] = $ k;
It should be written as follows: $ I ++;
$ Array [$ I] = $ j;
$ Array [$ I] = $ k;
$ I ++;


9.7. how to write if and else if
When multiple conditions exist in a condition statement and the variable value is determined, you need to put the variable judgment statement before other condition statements.

Example: The following example is invalid.

The code is as follows:


If (function_exists ('OB _ gzhandler') & $ val = 1 ){
}
It should be written as follows: if ($ val = 1 & function_exists ('OB _ gzhandler ')){
}
In PHP, else if and elseif have the same effect. But to ensure code uniformity (there are also rumors that else if will be unstable), we need to leave no space between elseif: if ($ bool = 2 ){
} Elseif ($ n = 1 ){
}


9.8. input variable initialization
Whether it is a function parameter or a variable passed through a URL, you must pre-process it and set the default value before calling it.

The string must be trim and escaped. if the value of the variable is within our expected range, the variable's invalid value must be processed accordingly; intval or floatval is required for numeric variables.

9.9. require and include
When the program needs to contain files, we need to use require_once or include_once, and do not allow the use of require or include.

Only require_once can be used for files that must be included in the program, and include_once can be used for some files with conditional inclusion.

9.10. file name
All file names should be in lower case, and words are separated by a single underline.

For example, current_user.php is correct, but currentuser. php and currentUser. php are incorrect.

The name should be descriptive and concise. We naturally do not want to use lengthy sentences as file names, but it is better to enter a few more characters than wondering what a file is.

10. SQL syntax
10.1. SQL code layout
Since we are all using different editor settings, do not try to implement column alignment in SQL code. What we need to do is to break the statements into separate rows no matter what method we use. Here is an example of what the SQL code looks like. Pay attention to the usage of broken lines, uppercase letters, and parentheses.

For example:

The code is 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 value
Table names and field names in SQL statements do not use reserved words. variable names of all field values must be forcibly converted if they are numeric. Intval, floatval...

10.3. SQL select statement
The following code is not allowed if you know the fields to be queried:

SELECT * FROM 'mytable'
Instead, write the name of each field. do not be lazy. SELECT col1, col2, col3 FROM 'mytable'
To obtain the number of known records, use the LIMIT offset and count methods. do not use SELECT statements without LIMIT.

Use the SELECT count ([* | col1]) FROM method when the number of records needs or meets the conditions. do not use the SELECT col1 FROM method whenever possible.

When logical operations are required, try not to use not equal to or greater than or less.

10.4. SQL insert statement
SQL INSERT statements can be written in two different ways. You can also specify the columns to be inserted, or you already know the order of the columns in the data. you do not need to specify them in detail. We want to use the previous method, that is, to describe in detail which columns to insert. This means that the application code will NOT depend on the order of fields in the database, nor will it crash because we add other fields (unless they are specified as not null ).

For example:
# This is not what we want

The code is as follows:


Insert into 'mytable'
VALUES ('something', 1, 'else ')


# This is correct.

The code is as follows:


Insert into 'mytable' (column1, column2, column3)
VALUES ('something', 1, 'else ')


11. smarty syntax
11.1. delimiter
The delimiter is <{}>

11.2. double quotation marks and single quotation marks
To avoid dreamweaver rewriting the double quotation marks in the Smarty statement to ", we require that the double quotation marks are not allowed in the brackets of the Smarty statement, but single quotation marks are used.

Incorrect syntax:
<{If $ user_name eq ""}> Anonymous User <{/if}>
<{Insert name = "query_info"}>
Correct syntax:
<{If $ user_name eq ''}> Anonymous User <{/if}>
<{Insert name = 'query _ info'}>

11.3. conditional setting of HTML attribute values
When you need to set HTML element attribute values with conditions in the template, we require that all statements be included in double quotation marks. Error code:

The code is as follows:


<{If $ promote_price> 0}> "promote_goods"
<{Else}> "normal_goods" <{/if}>
><{$ Goods. goods_name}>



Correct syntax:

The code is as follows:


<{$ Goods. goods_name}>



11.4. condition modifier
In smarty, you can use eq, neq, gt, and lt to represent = and ,! =,>, <. Which one should we use?

=,! Is not allowed when the Smarty statement appears in the HTML tag ,! = This type of modifier, if this type of modifier is used, may cause this symbol or other HTML-related symbols to be automatically escaped by Dreamweaver.

In short, try to use such conditional modifiers as eq and gt to avoid direct use of =,>.

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.