joshchen_php Novice Advanced Master indispensable standard introduction _php skills

Source: Internet
Author: User
Tags case statement comments html form lowercase mixed modifiers

PHP specification
1. Why Coding Specifications
• Coding Specifications (Code conventions) are particularly important for programmers for several reasons:
1. In the life cycle of a software, 80% of the cost is spent on maintenance.

2. Almost no software is maintained by its original developers throughout its lifecycle.

3. Coding specifications 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 you've built.

2. Summary
• Use four spaces instead of tab indents.
• Remove the "?>" at the bottom of the php file.
• Each line program generally less than 80 characters, beyond the section, divided into multiple lines of writing.
• Write only one statement per line and do not allow multiple phrase sentences to be written on one line.
• Comments should be added to files and functions.
• Delete the annotated code in time.
• 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; separate JavaScript and CSS files are indented with 4 spaces.

3.2. Character encoding
All PHP, HTML files are saved as the 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. A blank line must be added between a relatively independent program block and a variable description
Example: The following example does not conform to the specification

Copy 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


One-line program requires less than 80 characters

Long statements are divided into multiple lines of writing, long expressions in the lower priority operator division of new lines, operators placed at the top of the new line, the new line to be divided into appropriate indentation, so that the layout is neat, the statement can be read.

If there are longer expressions or statements in loops, judgments, etc., then the Adaptive division is to be made, and the long expression should be divided into new rows at the lower precedence operator, and the operator will be placed in the first example of the new line:

Copy 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. One line to write a single statement


Multiple phrase sentences are not allowed to be written on one line, that is, 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 situation where it is lazy to knock out more than two characters to bring clarity to the code.

Example: The following example does not conform to the specification

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

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



4.7. Where do I put the braces?


The delimiter for the program block (curly braces ' {' and '} ') should be exclusive to one row and be in the same column, aligned to the left of the statement that references them.

At the beginning of the function body, the definition of the class, and the right brace in the IF, for, do, while, switch, and case statements should be placed at the end of the line, the opening brace should be in the same column as the beginning of the row with the right brace

Example: The following example does not conform to the specification

Copy Code code 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 space between symbols


This loosely written code is designed to make the code clearer.

Because the clarity produced by a blank space is relative, there is no need to leave a blank in a statement that is already very clear, and if the statement is clear enough the inner brackets (that is, the front of the left parenthesis and the right bracket) do not require spaces, and no spaces are required between the parentheses. In long statements, if you need to add a lot of space, then you should keep the whole clear, and in the local without spaces. Do not leave more than two spaces in a row when the operator is left blank.

Example: The following example does not conform to the specification

Copy 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 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 a space on both sides of the period (.).

Example: The following example does not conform to the specification

Copy Code code as follows:

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



4.10. Use of empty lines


No one wants to see the messy code crammed into a heap. We always use some blank lines when writing code to increase the readability of the code. A reasonable use of space to distinguish between code snippets will make the logic of the code more clear. We have imposed the following two types of empty lines:

<?php must have only 1 empty lines after
?> must have and only 1 empty lines before
• There must be 1 empty rows between two functions.
return, die, exit before adding a blank line if there are other statements.
In the code we do not allow extra spaces at the end of a line.

5. Note
5.1. File Header Template
/**
* Shopex Online Store documents Chinese name
* Description of the class or file, here you can use HTML
*
* @package
* @version $Id $
* @copyright 2003-2008 Shanghai ShopEx network Tech. Co., Ltd.
* @license Commercial
* =================================================================
*/
5.2. function Header Annotation
Each function should have a comment before it tells a programmer what it needs to know to use the function. A minimized annotation should include: the meaning of each parameter, the desired input, and the output of the function. The annotation should also give the behavior of this function under the wrong condition (and what is the specific error condition). (comments should ensure that) others do not have to look at the code of the function to confidently call this function in their own code.

In addition, adding comments for any tricky, obscure, or not-so-obvious code is certainly something we should do. Of particular importance to a document is any assumption made by your code, 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 happened (in the execution of the code).

Copy Code code as follows:

/**
* Some_func
* Description of the meaning of the function
* <div> This part can be freely entered <b>html</b></div>
* Because this is Phpdocument's agreement.
*
* @param mixed $arg 1 parameter one description
* @param mixed $arg 2 parameter two description
* @access Public
* @return BOOL
*/



5.3. Delete the repealed annotation


Uncomment the code to be deleted in time

5.4. Constants Plus Comments
For all variables and constants that have physical meaning, if their names are not fully annotated, they must be annotated when they are declared, indicating their physical meaning. Comments on variables, constants, and macros should be placed either adjacent or to the right.

Example:

Copy Code code as follows:

Active statistic Task number
Define (' Max_act_task_number ', 1000)

Define (' Max_act_task_number ', 1000);//Active statistic TASK number




5.5. Note Location


Note should be similar to the code described, the comments on the code should be placed above or to the right (comments on a single statement) adjacent to the position, should not be placed below, if placed above the code with the above is separated by a blank line.

Example: The following example does not conform to the specification

Example 1:

Copy Code code 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 plus Comment


Data structure declarations (arrays) that must be commented on. Comments on the data structure should be placed adjacent to it, not below, and the comment for each field in the structure is placed to the right of the field.

Example: As described in the following form

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


Global variables need to be commented on in more detail, including descriptions of their functionality, range of values, which functions or procedures are accessed, and considerations for access.

5.8. Annotation Indent
Annotations are indented in the same way as the described content, allowing the program to be neatly formatted and easy to read and understand.

Example: The following example does not conform to the specification

Copy Code code as follows:

function Example_fun () {
Code One comments
Codeblock One

Code two comments
Codeblock Two
}




Should be changed to the following layout:


Copy Code code as follows:

function Example_fun () {
Fdgfd
Codeblock One

Code two comments
Codeblock Two
}




5.9. Separate the annotation from the above code with a blank line


Example: The following example shows that the code is too compact.


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


For a case statement under a switch statement, if you go to the next case after processing a case because of special circumstances, you must add a clear comment before the cases statement is processed and the next one. This is more clear to the author of the program's intentions, effective prevention of the break statement without undue omission.

Example:

Copy Code code as follows:

Switch ($i) {
Case ' Cmd_init ':
echo "I equals 0";
Break
Case ' Cmd_start:
echo "I equals 1"//Now jump in case cmd_a
Case ' cmb_a ':
echo "I equals 2";
Break
}



5.11. Structure statement


The array variables that represent the structure in your code are declared in advance.

Example:

Copy Code code as follows:

function Example_fun () {
$student = Array (
' Name ' => ' xiaoming ',//Name
' Addr ' => ' detailed address ',//Address
' Sex ' => ' male ',//sex
' City ' => ' Shanghai '//Cities
)
}



5.12. Annotation format


Note Format uniformity, Single-line comments must use the '//... ", multiple lines using a pair of/*...*/

Example: The following example does not conform to the specification.

Copy Code code as follows:

/* If Receive_flag is TRUE/*
/* If Receive_flag is FALSE */
if ($receive _flag)



Should be written as follows:


Copy Code code as follows:

/* If Receive_flag is TRUE
If Receive_flag is FALSE */
if ($receive _flag)



5.13. The notes are mainly in Chinese


Note You should consider the factors that make the program easy to read and the appearance of typesetting, if you use the language if both Chinese and English, it is recommended to use Mandarin, unless you can express in a very fluent and accurate English.

6. Nomenclature rules
6.1. Prohibition of phonetic nomenclature
Phonetic notation is prohibited in the code.

6.2. Variable naming
The variable name should be all lowercase, and the 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 than to wonder what a variable is for.

6.3. Function naming
Use lowercase names separated by a single underline between words, allowing verb-verb phrases to be named for functions that perform an action. If it is an OOP method, you can have only verbs (nouns are the objects themselves). Allows you to name the system table function.

Example:

Copy 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 has
For private methods, start with _.

6.4. Loop 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, $k, and so on. This specification does not apply if the loop counter is a variable that already exists and has a meaningful name.

For example:

Copy 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 such 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 operator, and use the parentheses to specify the order in which the expressions are operated, avoiding the default precedence. Prevents misunderstanding when reading the program and prevents the program from error due to default priority and design ideas.

Example: An expression in the following statement

Copy 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) There is no error, but the statement is not easy to understand; $a | $b &lt; $c &amp; $d = $a | ($b &lt; $c) &amp; $d,


(3) caused the error of judgment condition.

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

Example: The following program has poor readability.

Copy 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 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 source program in the more closely related code should be as adjacent


Easy to read and find programs.

Example: The following code layout is not reasonable.

Copy Code code as follows:

$rect->length = 10;
$char _poi = $str;
$rect->width = 5;



It may be clearer if you write in the following form.


Copy Code code 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. function
8.1. The validity check of interface function parameter
The validity check of function parameter should be responsible by the caller of function, the interface function does the necessity legality check (do not enforce).

Summarized as: The main outside, supplemented within, not mandatory.

8.2. Function scale
The size of the function is limited to 100 lines, excluding comments and space lines.

8.3. A function completes only one function
8.4. Do not design multi-purpose functions
In addition to the scheduling function, the functions set in a function, it is likely to make the function of understanding, testing, maintenance, etc. become difficult

8.5. Multiple pieces of code to repeat the same thing
If multiple pieces of code do the same thing over and over again, there may be a problem with the division of the function. If the code has a material connection between the statements and completes the same functionality, consider constructing the code into a new function.

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

The ternary operator should only be used to do simple things. They're just for assignment, not for function calls or anything complicated. 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: the appropriate place 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. means that the variable is not initialized and will be an error. This is the easiest question to show when you check what variables the HTML form passes. These errors can be checked by using the embedded isset () or empty () function to check whether a variable is set to avoid it.

Example: Old-fashioned
if ($forum) ...
New method: if (!empty ($forum)) ...
if (Isset ($forum)) ...

9.4. Reference string
There are two different ways of referencing strings in PHP--using single quotes or using double quotes. The main difference is that the parser performs variable substitution in a string enclosed in double quotes, but does not execute in a string enclosed in single quotes. Therefore, you should always use single quotes, unless you do need to make variable substitutions of strings. In this way, we can avoid having the parser parse a bunch of strings that don't 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 quotes. Again, that will only add unnecessary work to the parser. In any case, be aware that almost all the 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 Code code 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 code 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 a reference character for readability, be aware that all of these variables need to be surrounded by {}: $str = "This is ' {$what} ' with no variables for the parser to find."

9.5. The key name of the associative array
In PHP, using a string that is not enclosed in quotes can be run as a key name for an associative array. We don't want to do this--in order to avoid confusion, this string should be enclosed in quotes. Note that this is only the case when we use a 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. Simplified operator
Simplified self-increasing ($i + +) and self-subtraction ($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 one line. Using them in expressions (convenience) is not enough to have headaches when debugging.

Example: The following example does not conform to the specification

Copy 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 conditions in a conditional statement have multiple, and a variable value is judged, it is necessary to place the judgment statement of the variable before other conditional statements.

Example: The following example does not conform to the specification

Copy Code code as follows:

if (function_exists (' Ob_gzhandler ') && $val = = 1) {
}
Should be written as follows: if ($val = = 1 && function_exists (' Ob_gzhandler ')) {
}
While in PHP, else if and ElseIf are essentially the same. But for the sake of the uniformity of the code (there are also rumors that else if there is an unstable situation), we require that no spaces be preserved between ElseIf: if ($bool = = 2) {
}elseif ($n = 1) {
}



9.8. Initialization of input variables


Whether it is a parameter of a function or a variable passed by a URL, you must preprocess it and set a default value before calling it.

The string must be handled with trim and escape, and if the value of the variable is within our expected range, the variable's illegal value should be handled appropriately, and the intval or floatval should be processed for the numeric variable.

9.9. Require and include
When you need to use the include file in your program we require the use of require_once or include_once, and we do not allow require or include.

Only require_once can be used for files that a program must contain, and only include_once can be used when referencing certain conditionally contained files.

9.10. File naming
The file name should be all lowercase, and the 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 characters than to wonder what a file is for.

SQL syntax
10.1. SQL Code Layout
Now that we're all using different editor settings, don't try to do things like doing column alignment in SQL code. The way to do this is to break the statements into separate lines, regardless of the method. Here's an example of what the SQL code should look like. Note Where to break, capitalize, and bracket usage.

For example:

Copy 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 of all field values, and if they are numeric, you need to force type conversions. Intval,floatval ...

10.3. SQL SELECT statement
The following code is not allowed if the field that you want to query is known to be used:

SELECT * from ' mytable '
Instead, write down each field name, please don't be lazy. SELECT col1, col2, col3 from ' mytable '
When you need to get the number of known records, use LIMIT offset, count, and try not to use a LIMIT-free SELECT statement.

Use select count ([*|col1]) from, and try not to use the Select col1 from method, if the number of records is required or satisfied.

When you need to do logical operations, try not to use not equal to, you can use more than or less than the way.

10.4. SQL INSERT statement
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:
# That's not what we want.

Copy Code code as follows:

INSERT into ' mytable '
VALUES (' Something ', 1, ' Else ')



# that's right.


Copy Code code as follows:

INSERT into ' mytable ' (Column1, Column2, Column3)
VALUES (' Something ', 1, ' Else ')



Smarty Grammar
11.1. Defining character


The defining character is &lt;{}&gt;

11.2. Double quotes, single quotes
To prevent Dreamweaver from rewriting the double quotes in the Smarty statement to ", we require that double quotes not be allowed in the curly braces of the smarty, but instead use single quotes."

Wrong wording:
<{if $user _name eq ""}> anonymous user <{/if}>
<{insert name= "Query_info"}>
The correct wording:
<{if $user _name eq '}> anonymous user <{/if}>
<{insert name= ' Query_info '}>

11.3. Conditionally Set HTML property value
When you need to conditionally set HTML element attribute values in a template, we require that all statements be enclosed in double quotes. Wrong code:

Copy Code code as follows:

<div class=
<{if $promote _price>0}> "Promote_goods"
<{else}> "Normal_goods" <{/if}>
><{$goods .goods_name}></div>



The correct wording:


Copy Code code as follows:

<div class= "<{if $promote _price gt 0}>promote_goods
<{else}>nomarl_goods<{/if}> "><{$goods .goods_name}></div>



11.4. Condition modifiers


In Smarty, EQ, NEQ, GT, lt etc. can be used to represent = =,!=, &gt;, &lt; respectively. So what kind of thing 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 may cause the symbol or other HTML-related symbols to be automatically escaped by Dreamweaver.

In short, try to use the EQ, GT and other such conditional modifiers, 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.