PHP coding track

Source: Internet
Author: User
Tags coding standards php coding standards
PHP coding standards in order to make our code more readable and maintainability, but also to write less comments, we hope to achieve the goal of "CodeasDocument" through standardized naming and code writing. All php files in the Yigao e-commerce system must comply with the encoding rules stipulated in this document. At the same time, we added a standard check on the SVN server, such as storing the PHP code specification in the submitted code.

To make our Code more readable and maintainable, and to write less comments, we hope to achieve the goal of "Code as Document" through standardized naming and Code writing. All PHP files in the Yigao e-commerce system must comply with the encoding rules stipulated in this document. At the same time, we added a standard check on the SVN server. if the submitted code contains invalid code, SVN will return an error message. Read the SVN error message carefully. the prompt contains detailed error files, number of lines, and non-compliant descriptions.

If necessary, contact the project administrator.

Editor settings
  1. Code indent: all indentation replace Tab tabs with spaces. each indent contains four spaces.
  2. File encoding: all php files are saved as UTF-8 (No BOMIs not allowed to use ANSI.
Naming convention variable naming

The variable name is named in the hump mode. The first letter is lowercase and the first letter of the subsequent word is uppercase. For example:

$ CurrentUser is correct,$ CurrentuserAnd$ Current_userIncorrect.
$ RequestUrl is correct,$ RequestURLIncorrect.

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.

Constant name

Constant naming is composed of uppercase letters and underscores (_), for example, ORDER_TYPE.

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 ($i = 0; $i < $outerSize; $i++) {     for ($j = 0; $j < $innerSize; $j++) {        foo($i, $j);     }  }
Function name

The function should also be descriptive. Here we are not using C programming. We do not want to write functions such as "stristr. Same as above, words are classified by hump. It is best to have a verb somewhere in the function name. Good function names, such as printLoginStatus (), getUserData (), and so on.

Function parameters

Parameters follow the same conventions as variable names. We don't want a bunch of such functions: doStuff ($ a, $ B, $ c ). In most cases, we want to know how to use the function just by looking at the declaration of the function. The number of parameters must be limited to five, and more than five parameters can be transmitted using arrays.

Class
  • Class name: It must first be a meaningful English word or phrase. The first letter of the class name is capitalized, and the first letter of each word needs to be capitalized.
  • Class member variables: The names of member variables are consistent with those of variables.
  • Class Member method: The method name must be the same as the function name.Note that: For private methods, the method name must start with an underscore.
Summary

The basic philosophy here is not to hurt code clarity for laziness. However, some common sense must be used to grasp this balance. for example, printLoginStatusForAGivenUser () is too powerful-this function is named printUserLoginStatus () better, or just printLoginStatus ().

Code layout file header

In addition to template files and third-party PHP programs, all PHP file headers must contain a standard file header to describe the purpose of the file and other information. For example:

 ?

For details about the copyright and other labels, refer to the instructions in PHP plugin ention.

Comment writing

According to the popular annotation writing method, we need to write the annotation of the code segment in the following way:

Block-level notes:
This annotation is used to describe the usage of the following multiple lines. generally, a code block is distinguished by blank lines. The statement is as follows:

/* Here is the content of the comment * // *** if there are too many comments * Please use this method to write */?

Line comment:
This annotation is used to describe the code to be modified. generally, both the annotation and the code are in the same line, for example:

$ UserInfo = $ user-> getInfo (); // obtain user details?
Braces !!!

There is a lot of controversy about the location of braces. In fact, they all have their own principles for all kinds of arguments, but basically everyone is the same. this is:Always use braces, No matter how short the statement is, always use braces. For example:

/* These are correct */if (condition) {doStuff () ;}while (condition) {doStuff () ;}for ($ I = 0; $ I <size; $ I ++) {doStuff ();}
?

For the location of braces, that is:The braces of classes, functions, and control statements are always in the same row.. For example:

class MyClass {    public function foo() {        if (cond) {            doSomething();        }    } }?
Use spaces before and after the symbol

This is another simple and easy step to keep the code readable without too much trouble. Whenever you write a value assignment, expression, and so on, you always keep a space between symbols. Basically, the code is written in English. Insert spaces between variable names and operators. Do not add spaces after the starting or ending arc. Do not add spaces before commas or semicolons. Some examples demonstrate this well. For example:

/* Each pair provides an error method, followed by the correct method. */$ I = 0; $ I = 0; if ($ I <7 )... if ($ I <7 )... if ($ I <7) & ($ j> 8 ))... if ($ I <7) & ($ j> 8 ))... do_stuff ($ I, "foo", $ B); do_stuff ($ I, "foo", $ B); for ($ I = 0; $ I <$ size; $ I ++ )... for ($ I = 0; $ I <$ size; $ I ++ )... $ I = ($ j <$ size )? 0: 1; $ I = ($ j <$ size )? 0: 1 ;?
Operator priority

Do you know the detailed priority of all operators in PHP? I don't know. Do not guess. Always use parentheses to force the priority of an expression so that you know what it will do. For example:

/* What is the result? Who knows? */$ Bool = ($ I <7 & $ j> 8 | $ k = 4);/* now you are sure what I am doing here. */$ Bool = ($ I <7) & ($ j <8) | ($ k = 4 )))?
Database naming rules
  • The names of databases and data tables are the same as those of classes, and are named in upper case. Note that:The names of all data tables must be in the plural format.
  • The names of all fields should be composed of descriptive words. the naming rules are consistent with the variable naming rules.
  • To work with the ORM model, we requireAll primary keys are named as IDs.
Writing other rules such as 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.

/* Correct syntax */if (1 ===$ val & function_exists ('OB _ gzhandler ')){......} /* incorrect syntax */if (function_exists ('OB _ gzhandler') & 1 ==$ val ){}
?

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 spaces between elseif:

 if (2 == $n) {    ... ...} elseif (1 == $n) {    ... ...}

In the above code, I used1 === $nThis method is not commonly used.$n === 1The purpose is to avoid writing an equal sign when we write a double equal sign incorrectly. PHP will not report an error, this will cause a waste of time in the debugging process.

We do not force such a statement here, but we strongly recommend that you:Place the constant on the left of the equal sign when writing the logical judgment equal.

If statement

To make the code look brief, the following simple if statement can be abbreviated:

// The usual method is if ($ a = $ B) {$ c = 'foo ';} // abbreviated form $ a === B & $ c = 'foo ';

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.