Home >Backend Development >PHP Tutorial >JoshChen_Indispensable introduction to PHP standards for novices and advanced experts_PHP tutorial

JoshChen_Indispensable introduction to PHP standards for novices and advanced experts_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:58:591157browse

PHP specifications
1. Why coding conventions
•Coding conventions are particularly important for programmers for the following reasons:
1. In the life cycle of a software, 80% of the cost is spent on maintenance.

2. Almost no piece of software is maintained by the original developer throughout its entire life cycle.

3. Coding standards can improve the readability of software and allow programmers to understand new code as quickly and thoroughly as possible.

4. If you release the source code as a product, you need to confirm that it is well packaged and clear, just like any other product that has been built.

2. Summary
•Replace tab indentation with four spaces.
•Remove the "?>" at the bottom of the PHP file.
•Each line of program is generally less than 80 characters, and the excess is divided into multiple lines.
•Only write one statement per line, multiple short statements are not allowed to be written in one line.
• Files and functions should be commented.
• Deprecated comment code should be deleted promptly.
•The naming of variables and functions should be standardized.

3. Editor Settings
3.1. Indentation
Use spaces instead of tabs for all indents. PHP files use a 4-space indentation, HTML files and Javascript code embedded in HTML files use a 2-space indentation, and individual Javascript and CSS files use a 4-space indentation.

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

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

4.2. Blank lines must be added between relatively independent program blocks and after variable descriptions
Example: The following example does not comply with the specification

Copy code The code is 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 should be divided into Multi-line writing
One line of program must be less than 80 characters

Longer statements should be written in multiple lines. Long expressions should be divided into new lines at low priority operators. The operators should be placed at the beginning of the new line. The divided new lines should be appropriately indented so that The layout is neat and the sentences are readable.

If there are long expressions or statements in loops, judgments, etc., they must be divided appropriately. Long expressions must be divided into new lines at low priority operators, and the operators must be placed at the beginning of the new line. Example :

Copy code 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 < , $j++){
... // program code
}

4.4. Only write one statement per line
Multiple short statements are not allowed to be written in one line. That is, only write one statement per line. Example: The following example does not comply with the specification

$rect->length = 0; $rect->width = 0;

should be written as follows:
$rect->length = 0;$rect->width = 0;4.5 . Always include curly brackets
This is another case where being too lazy to type two extra characters creates problems for code clarity.

Example: The following example does not comply with the specification


Copy code 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
Copy codeThe code is as follows:

if (condition){
do_stuff();
}
while ($condition){
do_stuff();
}
for ($i = 0; $i < $size; $i++){
do_stuff( ; :

switch (){
case '1':
..program
break;
case '2': ..program break;}
4.7. Where to put the braces
The delimiters of the program block (braces '{' and '}') should each be on their own line and in the same column. Also left aligned with the statements that refer to them.

The right brace at 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 line, and the left brace should be on the same line as the right brace. Heading in the same column

Example: The following example does not comply with the specification



Copy code

The code is as follows:

for (...)

{

 … // program code
}

if (...){ ... // program code}
function example_fun()
{
... // program code
}
should be written as follows: for (...){

... // 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, there is no need for spaces inside the brackets (that is, after the left bracket and before the right bracket) Add spaces. There is no need to add spaces between multiple brackets. In a long statement, if a lot of spaces need to be added, the overall statement should be kept clear and no spaces should be added locally. When leaving spaces for operators, do not leave more than two spaces in a row.

Example: The following example does not comply with the specification




Copy code


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 ); It should be written as follows:


Copy code

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 Concatenation
When using string concatenation, spaces must be added on both sides of the period (.).

Example: The following example does not comply with the specification



Copy code

The code is as follows:


$str = '';$str = '';

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


4.10. Use of blank lines
No one wants to see a bunch of disordered code. When we write code, we always use some blank lines to increase code readability. Reasonable use of spaces to distinguish code segments will make the logical flow of the code clearer. The blank lines we forcefully provide include the following two situations:

•?> There must be exactly one blank line before it
•There must be one blank line between two functions.
•If there are other statements before return, die, or exit, a blank line should be added.
We do not allow extra spaces at the end of lines in the code.

5. Comments
5.1. File header template
/**
* ShopEx online store file Chinese name
* Class or file description, you can use html here
*
* @package
* @version $Id$
* @copyright 2003-2008 Shanghai ShopEx Network Tech. Co., Ltd.
* @license Commercial
* ========================== =======================================
*/
5.2. Function header comments
There should be before each function Comments tell a programmer what they need to know to use this function. A minimal comment should include: the meaning of each parameter, the expected input, and the function's output. The comment should also describe the behavior of the function under error conditions (and specifically what error conditions are). (Comments should ensure that) others can confidently call this function in their own code without looking at the function's code.

Also, adding comments to any code that is tricky, obscure, or not obvious is definitely something we should do. Of particular importance to documentation are any assumptions your code makes, or preconditions for it to function correctly. Any developer should be able to look at any part of the application and determine within a reasonable amount of time what is going on.

Copy code The code is as follows:

/**
* some_func
* The meaning of the function
.
* * @Param Mixed $ ARG1 Parameter One Explanation
* @Param Mixed $ ARG2 Parameter Two Explanation
* @Access Public
* @Return Bool
*/


5.3 . Delete the abolished comments
The abolished comments and the commented code should be deleted promptly

5.4. Annotation of constants For all variables and constants with physical meaning, if their names are not fully self-explanatory, they must be commented to explain their physical meaning when declared. Comments for variables, constants, and macros should be placed adjacent to or to the right above them.


Example:


Copy code 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

Comments should be close to the code they describe, and comments on the code should be placed there The position adjacent to the top or right (comment for a single statement) cannot be placed below. If it is placed above, it must be separated from the code above it by a blank line.

Example: The following example does not comply with the specification

Example 1:


Copy code 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. Data structure declaration addition Comment
Data structure declaration (array) must be commented. Comments on the data structure should be placed adjacent to it, not below it; comments on each field in the structure should be placed to the right of this field.

Example: Explain as follows


Copy code 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 notify user the No.7 network can not transmit this message
N_UNITDATA_REQ => 3 // sccp user's unit data transmission request
)

5.7. Global variable comments
Global variables should have more detailed comments, including descriptions of their functions, value ranges, which functions or procedures access them, and precautions when accessing them.

5.8. Comment indentation
Comments should be indented in the same way as the described content, which can make the program layout neat and facilitate the reading and understanding of the comments.

Example: The following example does not comply with the specification

Copy code The code is as follows:

function example_fun(){
// code one comments
CodeBlock One

// code two comments
CodeBlock Two
}


should be changed to the following layout:
Copy code The code is as follows:

function example_fun(){
//fdgfd
CodeBlock One

// code two comments
CodeBlock Two
}


5.9. Separate comments and the code above them with blank lines
Example: The following example seems to be too codey compact.
Copy code The code is as follows:

// code one comments
program code one
// code two comments
program code two
should be written as follows // code one comments
program code one

// code two comments
program code two


5.10. Continuous case comments
For the case statement under the switch statement, if it is necessary to enter after processing a case due to special circumstances When processing the next case, a clear comment must be added after the case statement is processed and before the next case statement. This makes the programmer's intentions clearer and effectively prevents the break statement from being omitted for no reason.

Example:

Copy code The code is as follows:

switch ($i){
case 'CMD_INIT' :
echo "i equals 0";
break;
case 'CMD_START:
echo "i equals 1";// now jump into case CMD_A
case 'CMB_A':
          echo "i equals 2";
     break;
}

5.11. Structure declaration
Array variables representing structures in the code must be declared in advance.

Example:

Copy code The code is as follows:

function example_fun(){
$student = array(
'name' => 'Xiao Ming', //Name
'addr' => 'Detailed address', //Address
'sex' => 'Male', //Gender
        'city' => 'Shanghai' //City
  )
}

5.12. Comment format
The comment format is unified, single-line comments must use "// … …”, use a pair of /*…*/ for multiple lines

Example: The following example does not comply with the specification.

Copy code The code is as follows:

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

should be written as follows:
Copy code The code is as follows:

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

5.13. Comments should be mainly in Chinese
Comments should consider the factors of program readability and appearance layout. If the language used is both Chinese and English, it is recommended to use Chinese more, unless it can be expressed in very fluent and accurate English. .

6. Naming rules
6.1. Pinyin nomenclature is prohibited
Pinyin nomenclature is prohibited in the code.

6.2. Variable naming
Variable names should be all lowercase, and words should be separated by a single underscore.

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

Name should be descriptive and concise. Of course we don't want to use long sentences as variable names, but it's better to enter a few more characters than to wonder what a variable is used for.

6.3. Function naming
Use lowercase names separated by single underscores between words, allowing verb-object phrases to name functions that perform a certain operation. If it is an OOP method, it can only be a verb (the noun is the object itself). Allow table function naming.

Example:

Copy code 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

Copula list: is has
For private methods, it starts with _.

6.4. Loop Counters
The only case where a single-character variable name is allowed is when it is used as a loop counter. In this case, the outer loop's counter should always be $i. If there was a loop inside this loop, its counter would be $j, then $k, etc. If the loop's counter is an existing variable with a meaningful name, this specification does not apply.

For example:

Copy code 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 convention as variable names. We don't want a bunch of functions like this: do_stuff($a, $b, $c). In most cases, we want to know how to use a function just by looking at its declaration.

7. Readability
7.1. Priority of operators
Pay attention to the priority of operators, and use parentheses to clarify the order of operation of expressions to avoid using the default priority. Prevent misunderstandings when reading the program and prevent program errors caused by the default priority being inconsistent with the design idea.

Example: Expression in the following statement

Copy code The code is 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
Since $high << 8 | $low = ($high << 8) | $low,
$a | $b && $a & $c = ($ a | $b) && ($a & $c),

(1)(2) will not go wrong, but the statement is not easy to understand; $a | $b < $c & $d = $a | ($b < $c) & $d,
(3) caused an error in the judgment condition.

7.2. Avoid numbers and use constants
Avoid numbers that are difficult to understand and replace them with meaningful constants.

Example: The following program is poorly readable.

Copy code The code is as follows:

if ($trunk[$index]->trunk_state == 0){
$trunk[$index]->trunk_state = 1;
... // program code
}

should be changed to the following form.
Copy code 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. Closely related codes in the source program should be as adjacent as possible
to facilitate program reading and search.

Example: The following code layout is not reasonable.

Copy code The code is as follows:

$rect->length = 10;
$char_poi = $str;
$rect->width = 5;

It may be clearer if written in the following form.
Copy code The code is as follows:

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

8. Function
8.1. Legality check of interface function parameters
The legality check of function parameters should be the responsibility of the caller of the function, and the interface function should do the necessity legality check ( Not mandatory).

The summary is: outside is the main thing, internal is the supplement, and internal is not mandatory.

8.2. Function size
The size of a function is limited to 100 lines, excluding comments and blank lines.

8.3. A function only completes one function
8.4. Do not design a multi-purpose and comprehensive function
In addition to the scheduling function, a multi-functional function is likely to make the understanding, testing and maintenance of the function difficult. Waiting becomes difficult

8.5. Multiple sections of code repeat the same thing
If multiple sections of code repeatedly do the same thing, there may be problems with the division of functions. If there is a substantial relationship between the statements in this code and they complete the same function, then you can consider constructing this code into a new function.

9. Quality Assurance
9.1. Compatibility
9.2. Ternary operator
Ternary operator, only one level is allowed in a line of code

The ternary operator should only be used to do simple things. They are only suitable for assignment, not for function calls or anything complicated at all. If used incorrectly, they can affect readability, so don't obsess over using them to reduce typing.

Example: where they should not be used
(($i < $size) && ($j > $size)) ? do_stuff($foo) : do_stuff($bar);

Example: appropriate place to use them $min = ($i < $j) ? $i : $j;

9.3. Initialize variables
Variables should be initialized before use, and error_reporting will be added to E_NOTICE. This means that an error will be reported if the variable is not initialized. This problem most commonly arises when checking what variables are passed in an HTML form. These errors can be avoided by using the built-in isset() or empty() functions to check whether a variable is set.

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

9.4. Quoting Strings
There are two different ways to quote strings in PHP - using single quotes or using double quotes. The main difference is that the parser performs variable substitution in strings enclosed in double quotes, but not in strings enclosed in single quotes. Therefore, you should always use single quotes unless you really need to perform variable substitution on a string. This way, we avoid the hassle of having the parser parse a bunch of strings that don't need to perform substitutions. Likewise, if you use a string variable as part of a function call, you don't need to surround that variable in quotes. Again, that just adds unnecessary work to the parser. Regardless, be aware that almost all escape sequences in double quotes will not work in single quotes. If this convention makes your code difficult to read, be careful and feel free to break it.

Example: The following example does not comply with the specification

Copy code The code is as follows:

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

should be written as follows:
Copy Code 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 quotes as quotation marks for readability reasons, note that all variables must be surrounded by {}: $str = " This is '{$what}' with no variables for the parser to find."

9.5. Key name of associative array
In PHP, it is possible to use a string without quotes as the key name of an associative array. We don't want to do this - to avoid confusion, the string should be enclosed in quotes. Note that this is only the case when we use strings, not when we use variables. Example: The following example does not comply with the specification

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

9.6. Simplifying Operators
The simplified increment ($i++) and decrement ($i--) operators are the only simplifying operators that cause readability problems. These operators should not be used as part of an expression. However, they can be used on their own line. Using them in expressions is not enough debugging headache.

Example: The following example does not comply with the specification

Copy code The code is as follows:

$array[++$i] = $j;
$array[$i++] = $k;
should be written as follows: $i++;
$array[$i] = $j;
$array[$i] = $k;
$i++;

9.7. How to write if and else if
When there are multiple conditions in the conditional statement and there is judgment on variable values, you need to Variable judgment statements are placed before other conditional statements.

Example: The following example does not comply with the specification

Copy code The code is as follows:

if (function_exists('ob_gzhandler') && $val == 1){
}
should be written as follows: if ($val == 1 && function_exists('ob_gzhandler')){
}
Although in PHP else if and elseif The function is basically the same. However, for the sake of code uniformity (there are also rumors that else if will be unstable), we require that no spaces be retained between elseif: if ($bool == 2){
}elseif ($n = 1){
}

9.8. Initialization of input variables
Whether it is a function parameter or a variable passed through the URL, it must be preprocessed and default values ​​set before calling.

Strings must be trimmed and escaped, and if the value of the variable is within our expected range, the illegal value of the variable needs to be processed accordingly; for numeric variables, intval or Processing of floatval.

9.9. require and include
When we need to use include files in the program, we are required to use require_once or include_once, and require or include are not allowed.

Only require_once can be used for files that must be included in the program, and include_once can only be used when referencing certain files that are conditionally included.

9.10. File Naming
File names should be all lowercase, with words separated by a single underscore.

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

Name should be descriptive and concise. Of course we don't want to use long sentences as file names, but it's better to enter a few more characters than to wonder what a file is for.

10. SQL syntax
10.1. SQL code layout
Since we are all using different editor settings, don’t try to do things like column alignment in SQL code Trouble. What you do is, whatever method you use, break the statements onto their own lines. Here's an example of what SQL code should look like. Pay attention to line breaks, capitalization, and the use of parentheses.

For example:

Copy code 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 names and field values ​​
Avoid using reserved words in table names and field names in SQL statements; at the same time, the variable names of all field values, if they are numeric, require forced type conversion. intval,floatval…

10.3. SQL select statement
On the premise that the fields to be queried are known, the following code is not allowed:

SELECT * FROM `mytable`
The alternative is to write each field name, please don’t be lazy. SELECT col1, col2, col3 FROM `mytable`
When you need to obtain a known number of records, please use LIMIT offset, count, and try not to use SELECT statements without LIMIT.

When the number of records is required or meets the conditions, please use SELECT count([*|col1]) FROM and try not to use SELECT col1 FROM.

When you need to perform logical operations, try not to use not equal to, you can use greater than or less than.

10.4. SQL insert statement
SQL INSERT statement can be written in two different ways. Either you explicitly specify the columns to be inserted, or you already know the order of the columns in the data and do not need to specify them in detail. We want to use the former method, which is to specify which columns to insert. This means that the application code will not depend on the order of the fields in the database, nor will it crash if we add additional fields (unless, of course, they are specified as NOT NULL).

For example:
# This is not what we want

Copy code The code is as follows:

INSERT INTO ` mytable`
VALUES ('something', 1, 'else')

# This is correct.
Copy code The code is as follows:

INSERT INTO `mytable` (column1, column2, column3)
VALUES (' something', 1, 'else')

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

11.2. Double quotation marks and single quotation marks
In order to prevent Dreamweaver from rewriting the double quotation marks in Smarty statements as ", we require that double quotation marks are not allowed in Smarty curly braces, but single quotation marks are used.

Incorrect writing:
<{if $user_name eq ""}>Anonymous user<{/if}>
<{insert name="query_info"}>
Correct writing:
<{if $user_name eq ''}>Anonymous user<{/if}>
<{insert name='query_info'}>

11.3. Conditionally setting HTML attribute values ​​
When it is necessary to conditionally set HTML element attribute values ​​​​in the template, we require that all statements be included in double quotes. Wrong code:

Copy code The code is as follows:

<{if $promote_price> ;0}>"promote_goods"
<{else}>"normal_goods"<{/if}>
><{$goods.goods_name}>


Correct writing:
Copy code The code is as follows:

<{$goods.goods_name}>


11.4. The condition modifier
can be used in smarty to represent ==, !=, >, < with eq, neq, gt, lt, etc. respectively. So which one should we use?

When Smarty statements appear in HTML tags, modifiers such as == and != are not allowed. If such modifiers are used, this symbol or other HTML-related symbols may be automatically escaped by Dreamweaver.

In short, try to use condition modifiers such as eq, gt, etc., and avoid using == and > directly.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328171.htmlTechArticlePHP specifications 1. Why coding standards are needed? Coding conventions (code conventions) are particularly important for programmers. They are as follows Several reasons: 1. In the life cycle of a software, 80% of the costs are...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Share the entire process of successfully uploading images with CodeIgniter_PHP tutorialNext article:Share the entire process of successfully uploading images with CodeIgniter_PHP tutorial

Related articles

See more