In order to improve work efficiency, ensure the validity and rationality of the development, and maximize the readability and reuse of the program code, improve communication efficiency, need a code writing specification. Let's develop good coding habits while reducing bugs in your code.
Clevercode has compiled some specifications. This specification contains rules for naming specifications, code indentation rules, control structures, function calls, function definitions, annotations, include code, PHP tags, and often most naming in PHP development.
1 file formats
1.1 File Markers
All PHP files, whose code tags use full PHP tags, are not recommended for short labels, such as:
<?php //Recommended echo ' Hello World '; ? > <? The short label format is not recommended for Echo ' Hello World '; >
1) The short label format is easy to confuse with XML, and not all PHP versions and servers default to support or open the short label option (starting with PHP5.4, the short label option in php.ini does not affect the use of the short label). For files that contain only PHP code,?> is ignored at the end of the file. This is to prevent extra spaces or other characters from affecting the code.
2) This problem actually occurs only when the compression or cache output is not turned on, for example:
php.ini-suppress the compression output and cache output
Zlib.output_conpression = Offoutput_buffering = Off
foo.php, note that at this time there are some spaces or newline characters fall after, of course, this on the page is not to see
to the.
<?php $foo = ' foo '; ? >
index.php, while containing the foo.php, has actually output some space or newline.
<?php include ' foo.php '; Session_Start (); ? >
You will see a warning (warning): "... Cannotsendsessioncachelimiter-headersalreadysent ... "
1.2 File and directory naming
Both the program file name and the directory name are named in a meaningful English language, with no pinyin or meaningless letters, only letters, numbers, draw lines, and middle line characters are allowed, and must end with ". PHP" (except for template files).
Class Uniform adoption
demotest.php
2 Naming conventions
2.1 Variable naming
Variables in PHP are represented by a dollar sign followed by a variable name. Variable names are case-sensitive. A valid variable name begins with a letter or a lower line, followed by any number of letters, numbers, and lines. Normal regular expressions will be expressed as: [a-za-z_\x7f-\xff][a-za-zo-9_ ' x7f-\xff], and non-ASCII characters such as Chinese should not be used in variables.
2.1.1 Program overall
The whole program is named after the hump, starting with lowercase letters, and naming to make sense, such as:
function DisplayName ($name) { echo $name; }
2.1.2 PHP global variable key value
PHP global variable keys are named in the middle using the hump method on both sides.
2.1.3 Common variables
The common variable is used in the whole hump method,
Name by convention and avoid using commonly used keywords or words with ambiguous meanings. Variables should be dominated by nouns.
String: $myName
Array: $myArray
Not recommended:
$yes: It should not be used as a bool type, because the variables are likely to be changed, which may make syeszflase, and make their code logic confusing.
$sex: With vague meaning and not authentic English words, the name of the gender should be $gender.
Name of 2.1.4 function
Function names have to be meaningful, and you'll know what to do at a glance, as well as abbreviations. It is suggested to use verbs or verbs plus adjectives
Naming methods, such as ShowMsg. The following function names are not recommended:
Getpublishedadvertisementbycategoryandcategoryldandposition ()
The function name above can be refined to:
GetAd ($category, $categoryid, $position, $published)
For example, 1) class public functions:
Public Function Dogetusername ($job)
For example, 2) class private function, beginning with "_":
Private Function _dogetusername ($job)
For example, 3) class protection function, beginning with "_":
protected function _dogetusername ($job)
Properties in the 2.1.5 class
The variables in the class conform to the naming conventions of ordinary variables.
For example 1) public properties, static properties:
Public $userName = ' Clevercode '; static $userType = Array (All-in-all);
For example 2) private attributes, beginning with "_":
Private $_username = ' clevercode ';
For example, 3) protect attributes, beginning with "_":
protected $_username = ' Clevercode ';
For example 4) constants, all uppercase, separated by "_":
Const TYPE_GZ = 4;
2.2 Database naming
2.2.1 Library naming
1) Use lowercase letters. (Windows is case-insensitive, Linux is case-sensitive, for library porting compatibility, so all lowercase)
2) Multiple words, separated by "_" between words.
For example:
Db_user,db_system.
2.2.2 Table naming
1) The table names are in lowercase letters.
2) The table name uses a uniform prefix, and the prefix cannot be empty (modular, and can effectively circumvent the MySQL reserved word).
3) Use the "_" interval for table names that consist of multiple words.
For example:
Pre_users,pre_user_shop
2.2.3 table field naming
1) All are named with lowercase letters.
2) Multiple words are segmented (important) without drawing lines.
3) If necessary, prefix the characters commonly used segment with the first letter of the table name.
4) Avoid the use of keywords and reserved words, except for the conventional.
For example:
Username,newsid,userid,logid
3 Annotation Specifications
3.1 File comments
File comments are usually placed in the header of the entire PHP file, including file copyright, author, date of writing, version number, etc.
Important information. PHP, you can refer to the Phpdocument specification, easy to use the program to automatically generate documents.
File annotations Follow these rules:
1) must contain a description of the program;
2) must contain the author;
3) must contain copyright;
4) The name of the file must be included;
5) can contain written date;
6) can contain version information;
7) can contain important usage instructions, such as the calling method of the class, considerations, and so on.
For example:
<?php /** * systemuser.php * * System user Action * * Copyright (c) http://blog.csdn.net/ Clevercode * * Modification: *-------------------- * 2015/5/11, by Clever Code, Create *
3.2 Class and interface annotations
The comments for classes and interfaces should be as concise as possible. As a general rule, a file contains only one class, and in class annotations it is usually not necessary to add information such as the author and version, plus the visibility and simplified description. If the file comment is sufficiently detailed, you can not write a comment to the class. If there is an implementation class for both interfaces and interfaces, it is common practice to annotate only in the interface.
3.3 Methods and function comments
Comments on methods and functions are written in front of the class that typically needs to be marked for visibility, parameter types, and return values
For example 1:
/** * Compare old and new data * * @param bigint $userid person number * @param array $oldMap old data * @param array $newMap new data ( Output parameter) * @return string successfully returns ' OK ', Failure returns error message * /public static function Diffrecommendinfo ($userid, $oldMap, & $newMap) { }
For example 2:
/** * Insert log data * * @param bigint $data [' userid '] User number * @param array $data [' logintime '] login time * @return String successfully returned ' OK ', failed to return error message * /public static function Insertlogdata ($data) { }
3.4 Action Comment
Since we are all using the Zend development model, when the action is the entry of the HTTP request processing logic, it is bound to pass parameters such as Get,post. Can be commented as follows.
For example 1) without get,post passing parameters:
/** * Auto Set name * * @return void * /Public Function autosetaction () { }
For example 2) there is a get pass parameter when:
/** * Get user name * * @get int $userid user number * @get int $currpage current page * @get int $pagesize * * @return void * /Public Function getusernameaction () { }
For example 3) There are post pass parameters when:
/** * Delete User * * @post int $userid user number * @return void * /Public Function deleteuseraction () { }
3.5 Single-line Comment
1) write in front of the commented code, not behind. However, for single-line statements, it is customary to place comments at the end of a statement, or to write them on rows.
2) for large-segment annotations, use the/**/format, which is usually used in file and function comments, and the code internally uses//annotations, because it is simple to write.
For example:
Name
$name = ' Clevercode ';
4 Code Style
4.1 Indents and spaces
When writing code, you must be aware of the code's indentation rules:
1) Use 4 spaces as indents instead of tab indents (as can be pre-set in UltraEdit).
2) When assigning a variable, leave a space around the equal sign.
For example:
$name = ' clevercode ';//Recommended
$name = ' clevercode ';//Not recommended
To minimize workload and keep your code beautiful, we recommend that you use a large IDE to manage your code. For example, in Zend Studio, the code is formatted with the CTRL+SHIFT+F key combination.
4.2 Statement break
The following principles should be followed in code writing:
1) Try to ensure that the program statement line is a sentence;
2) Try not to make a line of code too long, general control in 80 characters or less;
If one line of code is too long, use a similar. = method to write lines;
When performing SQL statement operations on a database, try not to write SQL statements inside a function, but first define SQL with variables
statement, and then invokes the defined variable in the function that performs the operation.
For example:
Code segmentation $sql= "Selectusername,password,address,age,postcode from test_t"; $sql. = "Whereusername=${user}"; $ret = Mysql_ Query ($sql);
3) A function is controlled within 200 lines;
4) if up to 3 layers are nested;
Not recommended
if () { if () {if ( ) { if () }}}}
5) cycle up to 3 layers.
Not recommended for ( ) {for () {for () {for ( ) { ... }}}}
6) If or for a block of statements with only one line, plus {}. When there is a change in the statement will cause unnecessary bugs.
Recommended If ($a = = 1) { echo 1; } If ($a = = 1) echo 1 is not recommended;
4.3 Blank line
1) empty lines between functions and functions.
2) The same function is different from the logical block between the empty lines, look at the different logical blocks more clearly organized.
4.4 Function Structure
Usually a function is divided into three parts. The first part: checking parameters; Part two: processing logic; Part Three: returning results.
For example:
/** * Delete log through UID * * @param string $uid user uid * @return string successfully returned ' OK ', failed to return error message */public static function Deletelogbyuid ($UID) { //First step: Check parameters. Prevent the handling of partial exceptions, such as $uid is an incoming array (); if (!is_numeric ($uid)) { return '!is_numeric ($uid) '; } Step two: Handle the logic. $affected = $userLogTable->delete (' where UserID = '. $uid); Step three: Return the result. Let the caller know if the process is working properly. if ($affected) { return ' OK '; } Return ' delete error! '; }
4.5 function return function
Functions that require a client:
return value
$ret = Array (' Code ' = 1,msg=> ', data = Array ());
4.6 Better Habits
In your code, you can make your code more elegant by using the notation outlined below.
1) Use the constants that already exist in PHP, rather than defining them yourself, for example:
Echo$meg. " \ r \ n "; echo$msg,phpjeol;
In PHP, Php_eol is a predefined constant that indicates the end of a line, and using Php_eol makes the code more portable as the system is used.
2) more detailed comments.
Annotations are an art, and good annotations can be more exciting than code. Don't worry about the efficiency issue. The effect of a comment on the code
Rate, followed by bulk deletion of comments in the code in the formal product. Note the typical representation of the Acme and Perfection is the source code of various products of Apache organization.
3) Do not abuse grammatical sugars.
The grammatical sugar is the unspoken rule in the language, that is, the grammar which does not have the universal representation. Little use of grammar sugar will taste sweet
Head, heavy use is a disaster.
For example, the following code, readability is poor;
$a $a-$b:3&& $c && $d = 1;