Home >Backend Development >PHP Tutorial >JoshChen_Indispensable introduction to PHP standards for novices and advanced experts_PHP tutorial
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
if (!valid_ni(){
... // program code
}
$repssn_ind = $ssn_data['index]->repssn_index;
$repssn_ni = $ssn_data[index]->ni;
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 :
$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
}
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.
for (...)
{ … // program code
}
}
if (...){
... // program code
function example_fun(){
... // program code
}
4.8. Use spaces between symbols
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.
Copy code
$i=0;
if($i<7) ...if ( ($i < 7)&&($j > 8) ) ...
for($i=0; $i<$size; $i++) ...
should be written as follows: $str = ' ';
•
•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.
Example:
5.5. Comment position
Example 1:
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
// code two comments
CodeBlock Two
}
// code two comments
CodeBlock Two
}
// code two comments
program code two
Example:
Example:
Example: The following example does not comply with the specification.
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:
function print_record($rec_ind)
function input_record()
function get_current_color()
function is_boy()
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:
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
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.
if ($trunk[$index]->trunk_state == TRUNK_IDLE){
$trunk[$index]->trunk_state = TRUNK_BUSY;
... // program code
}
Example: The following code layout is not reasonable.
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
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
Example: The following example does not comply with the specification
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:
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
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:
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.