PHP Coding Specification

Source: Internet
Author: User
Tags empty end expression functions sql numeric value string strcmp
Code | Code 1. Introduced
1.1. The importance of standardization
The problem of standardization in some ways gives everyone a headache and makes everyone feel like they're in the same situation. This helps to keep these recommendations evolving across a number of projects, and many companies have spent many weeks arguing with each other on a child-by-word basis. Standardization is not a special personal style, it is completely open to local improvement.
1.2. Advantages
When a project tries to comply with common standards, it has the following benefits:
· Programmers can understand any code and find out the state of the program.
· Newcomers can quickly adapt to the environment
· Prevent new people from getting in touch with PHP to create a style and develop a lifelong habit for the sake of saving time
· Prevent new contacts in PHP from making the same mistakes again and again
· In a consistent environment, people can reduce their chances of making mistakes.
· Programmers have a consistent enemy.
1.3. Disadvantages
· Because standards are made by people who don't know PHP, standards usually look silly.
· Because the standard is different from what I do, the standard usually looks silly.
· The standard lowers creativity
· Standards are not necessary in a long period of cooperation among the population
· Standard forced too many formats
1.4. Discussion
The experience of many projects concludes that the adoption of programming standards can make the project more successful. Are standards the key to success? Of course not. But they can help us, and we need all the help we can get! To be honest, much of the controversy over a detailed standard stems mainly from conceit. Few decisions about a reasonable standard can be said to be lack of technical words, that's just the reason for the taste. So, be flexible and control your ego, and remember that any project depends on the effort of teamwork.
1.5. Explain
1.5.1. Standard implementation
The first thing you should do is find all the most important elements within the development team, and perhaps the standards are not appropriate for you. It may have outlined important issues, and there may be some strong objections to some of those issues. No matter what the circumstances, as long as the last smooth, people will be mature to understand that this standard is reasonable, and then other agents will find its rationality, and feel that with some reservations to follow this standard is worthwhile. If there is no voluntary cooperation, you can set requirements: The standard must be checked by the code. If there is no test, the solution is just a bunch of ridiculous people built on an imprecise basis.
1.5.2. Identity view
1. This is not workable;
2. Maybe it works, but it's neither practical nor boring;
3. It's true, and I told you so;
4. This is my first thought;
5. This should have been the case.
If you look at things with negative stereotypes, please keep an open mind. You can still make a conclusion that it's nonsense, but the way to make a conclusion is that you have to be able to accept different ideas. Please give yourself a little time to do it.
1.5.3. Four stages of the project
1. Database structure
2. Design
3. Data layer
4. HTML Layer
2. Naming rules
2.1. Proper naming
Naming is the core of program planning. The ancients believed that as long as they knew a person's real name, they would gain an incredible power over that person. As long as you think of the right name, it will give you and later people a stronger power than the code. Don't laugh!
A name is a long and far-reaching result in the ecological environment in which things are in place. In general, only programmers who know the system can get the most appropriate name for the system. If all the names are appropriate to their nature, then the relationship is clear, the meaning can be deduced, the average person's supposition can be expected.
If you find that your name is only small enough to match its counterpart, it's best to take a look at your design again.
2.2. Class naming
· Before you name the class (class), you should know what it is. If you can't remember what this class is by the clues provided by the class name, then your design is not good enough.
· A mixture of more than three words is easy to create confusion between the entities of the system, and then look at your design, try to use (CRC session card) to see if the name of the corresponding entity has so many functions.
· The naming of derived classes should avoid the temptation to have their parent names, a class whose name is related only to itself, regardless of what its parent class is called.
· Sometimes the suffix name is useful, for example if your system uses a proxy (agent), then a part is named "Download Agent" (downloadagent) to truly transmit information.
2.3. method and Function naming
· Usually each method and function performs an action, so naming them should be a clear indication of what they do: Replace Errorcheck () with checkforerrors () and replace datafile () with Dumpdatatofile (). Doing so also makes the function and data a more distinguishable object.
· Sometimes the suffix name is useful:
o Max-meaning is the maximum value that an entity can give.
o Cnt-The current value of a running count variable.
O Key-key value.
For example, Retrymax represents the maximum number of tests, and retrycnt represents the current number of retries.
· Sometimes the prefix name is useful:
O is-meaning to ask a question about something. Whenever people see is, they know it's a problem.
o get-meaning to obtain a numeric value.
o set-meaning to set a value
For example: Ishitretrylimit.
2.4. Do not use all capitals in abbreviations
· In any case, you can use the first letter to capitalize the remainder of the letter in lieu of all uppercase letters in place of abbreviations.
Use: Gethtmlstatistic.
Not used: gethtmlstatistic.
Reason
· When naming contains acronyms, people seem to have very different instincts. The unification rule is the best, so that the meaning of naming can be predicted completely.
To give a networkabckey example, note that C is supposed to be c in ABC or C in key, which is very puzzling. Some people don't care about this, others hate it. So you'll see different rules in different code so you don't know how to call it.
For example
Class Fluidoz//Don't write Fluidoz
Class Gethtmlstatistic//Don't write gethtmlstatistic
2.5. Class naming
· Use uppercase letters as a separate word, and all other letters use lowercase
· First letter of first name using uppercase
· Do not use underline ('_')
Reason
· According to many naming methods, most people think this is the best way.
For example
Class Nameonetwo
Class Name
2.6. Class Library naming
· Namespaces are being used more and more widely to avoid class name conflicts between different vendor and group library classes.
· When the namespace has not been adopted, in order to avoid class name conflicts, the general practice is to precede the class name with a unique prefix, two characters on it, of course, more than a few will be better.
For example
John Johnson's data structure class library can be prefixed with JJ, as follows:
Class Jjlinklist
{
}
Another compromise is to create a directory containing the class library (which Java does, in fact), which represents different namespaces in an irregular directory.
For example
A Microsoft database-related class library can be used to:
/classes/com/microsoft/database/dbconn.php
The Apache database-related class library can be used in:
/classes/org/apache/database/dbconn.php
2.7. Method naming
· Adopt A rule that is consistent with class naming
Reason
· Most people who use all the different rules find this to be the best compromise.
For example
Class Nameonetwo
{
function DoIt () {};
function HandleError () {};
}
2.8. Class attribute naming
· Attribute names should be prefixed with the character ' M '.
· The prefix ' m ' is followed by a class-name-consistent rule.
· ' m ' always modifies the beginning of the name, as if it were a reference at the beginning of ' R '.
Reason
· The prefix ' m ' prevents any conflicts between class properties and method names. Your method name and attribute name are often very similar, especially for accessing elements.
For example
Class Nameonetwo
{
function Varabc () {};
function ErrorNumber () {};
var $mVarAbc;
var $mErrorNumber;
var $mrName;
}

2.9. Parameter naming in method
· The first character uses a lowercase letter.
· All words after the first character are capitalized according to the first character of the class naming rule.
Reason
· You can distinguish between general variables in a method.
· You can use a name that is similar to a class name without conflicting duplicate names.
For example
Class Nameonetwo
{
function Startyourengines (
& $rSomeEngine,
& $rAnotherEngine);
}
2.10. Variable naming
· Use lowercase for all letters
· Use ' _ ' as the dividing line for each word.
Reason
· In this way, the scope of the variables in the code is clear.
· All variables look different in the code and are easily recognizable.
For example
function HandleError ($errorNumber)
{
$error = Oserr ($errorNumber);
$time _of_error = Oserr->gettimeoferror ();
$error _processor = Oserr->geterrorprocessor ();
}
2.11. Reference variables and function return reference
· Reference must be prefixed with ' R '
Reason
· Making variables of different types easy to identify
· It determines which method returns the object that can be changed and which method returns the immutable object.
For example
Class Test
{
var mrstatus;
Function dosomething (& $rStatus) {};
function &rstatus () {};
}
2.12. Global variables
· Global variables should be prefixed with ' G '.
Reason
· It is very important to know the scope of a variable.
For example
Global $gLog;
Global & $grLog;
2.13. Define naming/Global constants
· Global constants separate each word with ' _ '.
Reason
This is the tradition of naming global constants. You should be careful not to conflict with other definitions.
For example
Define ("A_global_constant", "Hello world!");

2.14. Static variables
· Static variables should be prefixed with ' s '.
Reason
· It is very important to know the scope of a variable.
For example
function test ()
{
static $msStatus = 0;
}

2.15. Function naming
· The function name uses the C GNU Convention, all letters use the lowercase letter, uses ' _ ' to divide the word.
Reason
· This makes it easier to distinguish between the associated class names.
For example
function Some_bloody_function ()
{
}

2.16. Error return detection rule
· Check all system call error messages unless you want to ignore the error.
· The system error text is defined for each system error message for include.
3. Rules of Writing
3.1. Curly Brace {} rule
Of the three main brace placement rules, there are two acceptable, as the first of the following is the best:
· Place curly braces in the same column below the keyword:
if ($condition) while ($condition)
{ {
... ...
} }
· The traditional Unix bracket rule is that the first bracket goes with the keyword, and the end bracket is in the same column as the keyword:
if ($condition) {while ($condition) {
... ...
} }
Reason
· Non-principled issues that cause intense controversy can be solved by compromise, and either approach is acceptable, but for most people it prefers the first one. The reason is the psychological study of the scope of things.
There are more reasons for liking the first one. If you use a character editor that supports bracket matching (for example, VI), the most important thing is to have a good style. Why? We say that when you have a large program and want to know where this chunk of program ends. You move to the beginning bracket, and the button editor will find the closing bracket that corresponds to it, for example:
if ($very _long_condition && $second _very_long_condition)
{
...
}
else if (...)
{
...
}
Moving from one program block to another requires only the cursor and your parentheses to match the key, and you don't need to find a matching bracket.
3.2. Indent/tab/space rules
· Use tab indents.
· Use three to four spaces to indent each level.
· No longer uses a method that indents as soon as one is needed. For the maximum number of indentation layers, there is no fixed rule, if the indentation layer is greater than four or five layers, you can consider the code factor decomposition (factoring).
Reason
· Many programmers support tabs.
· When people use tabs that differ too much, it makes reading code very laborious.
· So many people are willing to limit the maximum number of indentation layers, and it's usually never seen as a job. We believe that programmers will be wise to choose the depth of nesting.
For example
function func ()
{
if (something bad)
{
If (another thing bad)
{
while (more input)
{
}
}
}
}
3.3. Parentheses, keywords and function rules
· Do not put parentheses and keywords tightly together, to separate them with a space.
· Do not put parentheses and function names together.
· Do not use parentheses in return returns statements unless necessary.
Reason
· Keyword is not a function. If the parentheses are close to the function name and the keyword, the two can easily be considered as one.
For example
if (condition)
{
}

while (condition)
{
}

strcmp ($s, $s 1);

return 1;
3.4. Do not do the actual work in the object schema function
Do not do the actual work in the object schema constructor, the constructor should contain the initialization of the variable and/or the operation that does not fail.
Reason
· The construct cannot return an error.
For example
Class Device
{
function Device () {/* Initialize and other stuff */}
function Open () {return FAIL;}
};

$dev = new Device;
if (FAIL = = $dev->open ()) exit (1);
3.5. If Then Else format
Layout
This is decided by the programmer. The different pattern of curly braces produces a slightly different kind of view. A common approach is:
if (condition 1)//Note
{
}
else if (condition 2)//comment
{
}
else//Comment
{
}
If you use the else if statement, it is usually better to have an else block to handle other cases that are not handled. If you can put a record information note at else, even if there is no action.
Conditional formatting
Always place a constant on the left side of the equal/no equal sign, for example:
if (6 = $errorNum) ...
One reason is that if you omit an equal sign in the equation, the grammar checker will give you an error. The second reason is that you can find the value right away rather than finding it at the end of your expression. It takes a little time to get used to the format, but it's really useful.
3.6. Switch format
· When a case block is processed, it is transferred directly to the next case block and should be annotated at the end of the case block.
· The default case should always exist, it should not be reached, however, if it arrives it will trigger an error.
· If you want to create a variable, put all the code in the block.
For example
Switch (...)
{
Case 1:
...
FALL through
Case 2:
{
$v = Get_week_number ();
...
}
Break

Default
}
3.7 Continue,break and? The use
3.7.1. Continue and break
Continue and break are in disguise the covert goto method.
Continue and break like Goto, they are magical in code, so use them sparingly (as little as possible). Using this simple magic, readers will be directed to places that only God knows, for some undisclosed reasons.
The continue has two main problems:
· It can bypass test conditions.
· It can bypass an equal/unequal expression.
Take a look at the example below and consider where the problem occurs:
while (TRUE)
{
...
A lot of code
...
if (/* some condition * *) {
Continue
}
...
A lot of code
...
if ($i + + > Stop_value) break;
}
Note: "A lot of code" is necessary to make it easier for programmers to find errors.
From the above example, we can draw a further rule: continue and break mixing is the right way to cause disaster.
3.7.2.?:
The trouble is that people tend to try. And: A lot of code is crammed in between. The following are some clear connection rules:
· Place the condition in parentheses to separate it from other code.
· If possible, the action can be in a simple function.
· Put the action, "?", ":" On different lines, unless they can be clearly placed on the same line.
For example
(condition)? Funct1 (): Func2 ();

Or

(condition)
? Long statement
: another long statement;
3.8. Positioning of the declaration block
· The declaration code block needs to be aligned.
Reason
· Clear.
· Variable initialization of a similar code block should be listed.
· & should be close to the type, not the variable name.
For example
var $mDate
var& $mrDate
var& $mrName
var $mName

$mDate = 0;
$mrDate = NULL;
$mrName = 0;
$mName = NULL;
3.9. One statement per line
Unless these statements are closely related, only one statement per line is written.
3.10. Short method
The method code is limited to one page.
3.11. Record all empty statements
Always record a for or a while empty block statement so that you know clearly whether the code is missing or intentionally not written.

while ($dest + + = $src + +)
; VOID
3.12. Do not use the default method to test non-0 values
Do not test a non-0 value with the default value, that is, use:

if (FAIL!= f ())
Better than the following methods:

if (f ())

Even if FAIL can contain a value of 0, that is, the representation of PHP as false. When someone decides to use 1 instead of 0 as a failure return value, an explicit test can help you. You should use an explicit comparison if the comparison value does not change, for example: if (! $bufsize% strlen ($STR))) should be written as: if ($bufsize% strlen ($str) = = 0) to indicate the numeric value (not Boolean) of the test. A frequent problem is using strcmp to test a character equation, and the result will never be equal to the default value.
Non-0 tests take the approach based on default values, and other functions or expressions are subject to the following restrictions:
· Only 0 can be returned to indicate failure and cannot be/have other values.
· Name so that a true (true) return value is absolutely obvious, calling the function IsValid () instead of the Checkvalid ().
3.13. Boolean Logic Type
Most functions return 0 when FALSE, but play a non-0 value to represent TRUE, so do not detect a Boolean value with the 1 (True,yes, and so on) equation, instead of 0 (false,no, such) inequalities:

if (TRUE = = Func ()) {...
should be written:

if (FALSE!= func ()) {...
3.14. Usually avoid the embedded assignment
Sometimes in some places we can see embedded assignment statements, those structures are not a better less redundant, more readable method.

while ($a!= ($c = GetChar ()))
{
Process the character
}
The + + and--operators are similar to assignment statements. Therefore, for many purposes, the use of functions can have side effects. It is possible to use embedded assignment to improve run-time performance. In any case, programmers need to consider the trade-off between growth speed and reduced maintainability when using embedded assignment statements. For example:

A = B + C;
D = A + R;
Do not write:

D = (A = B + c) + R;

Although the latter can save a cycle. But in the long run, as the maintenance cost of the program grows, the writer of the program will gradually forget the code, and the optimal gain in the mature period can be reduced.
4. Help and sharing
4.1. Reusing the hard work of you and others
Cross-engineering reuse is almost impossible without a common structure. Objects meet their existing service requirements, and different processes have different service requirements environments, which makes it difficult to reuse objects.
Developing a generic structure requires a lot of effort to design in advance. When effort is unsuccessful, for whatever reason, there are several ways to recommend it:
4.2. Consult! Email the group for help
This simple method is rarely used. Because some programmers think that if he asks others for help, he will appear to be low level, this is silly! Do new and interesting work, do not over and over again do what other people have done.
If you need the source code for something, send an email to the group if someone has already done it. The result will be very pleasantly surprised Oh!
In many large groups, individuals are often unaware of what others are doing. You can even find someone who is looking for something to do, and is willing to write code for you, if people work together, there is always a gold mine.
4.3. Tell! When you're doing something, tell it to everyone.
If you do something reusable, let someone else know. Don't be shy, and don't hide your work to protect your pride. Once you get into the habit of sharing work results, everyone gets more.
4.4. Small code base
A common problem with code reuse is that people do not make libraries from the code they do. A reusable class may be hidden in a directory of programs and never be thrilled to be shared, because programmers don't split classes into libraries.
One of the reasons for this is that people do not like to make a small library, there are some incorrect feeling to the small library. Overcome this feeling, the computer doesn't care about how many libraries you have.
If you have some code that you can reuse and can't put into an existing library, then make a new library. If people really think about reusing, the library won't stay that small for a long time.
4.5. Knowledge Base
Many companies don't know what code is available, and most programmers still don't communicate what they've done or have been asking what code is available. The solution to this is to have an available knowledge base.
Ideally, programmers can go to a Web page, browse or query a packaged list of repositories to find what they want. It's a good idea to build a knowledge base system that programmers can automatically maintain. It would be better if you had a dedicated administrator to maintain the knowledge base.
Another approach is to automate the practice of generating knowledge bases from code. Use generic classes, methods, and headers (subsystem headers) as manuals or as an entry to the Knowledge base.
5. Writing notes
5.1. Tell a Story
Take your comments as a description of the system. And make your annotations can be resolved by the machine, put in a fixed format in the manual. The annotation of the class is part of the story, the name of the method, the annotation of the method, and the implementation of the method are also part of the story. All of these parts are woven together so that people can know exactly what you are doing and why.
5.2. Archive Notes
Annotations are meant to be archived, otherwise, if you put a comment in one place describing what you did and why you did it, only archaeologists could find this to be the most useful information. (How to file separate specifications)
5.3. Annotation structure
Each part of the project has a specific annotation structure. The annotation in the program, where the sample is presented as a specification, and the start of the keyword with the * @ is the end of the comment keyword.
5.3.1. Predefined keywords
Keyword meaning
Purpose represents what a class, property, method does or what it means.
Package Name Class name
Author author
Modifications modify record (number sequence is "no" + Date + "-" + serial number)
See reference
Method Name Methods Name
Parameter parameter name (including type)
return value (including type)
Attribute/variable Name property/variable name
Type attribute/variable types
Notes for 5.3.2. Class
/**
* @ Purpose:
* Access to the database class, ODBC as the universal Access interface
* @Package Name:database
* @Author: Forrest Gump gump@crtvu.edu.cn
* @Modifications:
* NO20020523-100:
* Odbc_fetch_into () parameter position second and third position exchange
* John Johnson John@crtvu.edu.cn
* @See: (Reference)
*/
Class Database
{
......
}
5.3.3. Method comment
/**
* @Purpose:
* Execute one query
* @Method Name:query ()
* @Parameter: String $queryStr SQL query string
* @Return: Mixed query return value (Result set object)
*/
function ($QUERYSTR) {...}
5.3.4. Attribute or variable annotation
/**
* @Purpose:
* Database connection user name
* @Attribute/variable Name:mdbusername
* @Type: string
*/
var mdbusername;
5.3.5. if (0) to annotate an external code block
Sometimes you need to annotate a large section of the test code, the easiest way is to use the if (0) Block:
function Example ()
{
Great looking code

if (0) {
Lots of code
}

More code
}
You cannot use/**/because annotations cannot be included internally, and large sections of programs can contain annotations.
5.3.6. Catalog Document
All directories need to have a Readme document, which includes:
· The functionality of the directory and what it contains
· An online description of each file (with link), and each description should also extract some of the attribute names of the file headers.
· Include settings, usage instructions
· Instruct people on how to connect to related resources:
O Source file Index
o online documentation
O Paper Document
O Design Documents
· Other things that are helpful to readers
Consider, when each of the original engineers has gone, a newcomer in 6 months, the lone frightened explorer through the project's source code directory tree, read the description file, the source file header description, etc. as a map, he should be able to cross the entire project.
6. Other
· The object oriented design method is adopted.
Reason
There is no doubt that this is the closest way to people's natural thinking, may be early to feel that there is no direct writing come fast, can try to retain their views? The show is behind you!
· Class is defined with a single file class, and the class name and filename are the same;
Reason
o More and more people have accepted this practice
O It turns out that this approach makes the logical structure of a project clearer
· In a class definition file, output statements such as ECHO and print must not appear outside the definition body;
Reason
This statement should appear as a bug.
· The page on the output page does not appear with SQL statements
Reason
This is the n-tier structure of the programming thought, each level of the task is different, although can be exercised ultra vires, may be so fast, but we do not agree to do so.
· Data for SQL execution must be tested for validity
Special symbols:
For MS SQL Server, the symbols for '%_[' are writing special meaning characters in SQL statements that need to be processed before SQL executes.
Script symbol:
For PHP script tags, such as the.?? ><%%><?php?><script lang<script language= "php" ></script&gt, you need to detect processing before entering the database.
Reason
This is a convention for database programming, as many reference books say, and here it needs to be emphasized.
· Try not to insert PHP code in HTML pages
The Loop code and the pure variable output (similar to the <?= $UserName?>) are excluded.
Reason
o What needs to be explained is that we work upstream, the page designer's work, if inserting the code in the page, will destroy the structure, this should be we need to avoid.
o Here the PHP code is only responsible for the display, superfluous code is clearly not supposed.
· Numbers that have no meaning
A naked number used in the source code is an incredible number, because including the author, within three months, no one has the meaning of it. For example:
if (= = = $foo) {Start_thermo_nuclear_war ();}
else if (= = = $foo) {Refund_lotso_money ();}
else if (= = = $foo) {infinite_loop ();}
else {cry_cause_im_lost ();}
What is the meaning of 22 and 19 in the example above? What would you think if a number changed, or if the numbers were simply errors?
The incredible number is that the programmer is an important symbol of amateur athletes who have never worked in a team environment or have to do something to maintain code, or they will never do such a thing.
You should use define () to give you a real name for the value you want to represent something, instead of using a naked number, for example:
Define ("President_went_crazy", "22");
Define ("we_goofed", "19");
Define ("They_didnt_pay", "16");

if (President_went_crazy = = $foo) {Start_thermo_nuclear_war ();}
else if (we_goofed = $foo) {Refund_lotso_money ();}
else if (They_didnt_pay = $foo) {infinite_loop ();}
else {happy_days_i_know_why_im_here ();}
Isn't it getting better now?
7. php File name extension
Common PHP file extensions are: HTML,. php,. PhP3,. PhP4,. Phtml,. Inc,. Class ...
Here we agree:
· All browsers visible page use. html
· All classes, function library files use. php
Reason
· The extension describes the type of data that the user will receive. PHP is interpreted as HTML.

8. PHP code Tag
Unified use of <?php, only output variables when <?= $username?>



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.