Php programming code specification learning notes (suitable for beginners)

Source: Internet
Author: User
We will introduce the php programming code specification from several methods, such as the reconstruction of common nouns and codes in naming conventions. below I will sort out some rules and then take some notes, I hope the article will help you. All the files named Category class are named. class. php is... we will introduce the php programming code specification from several methods, such as the reconstruction of common nouns and codes in naming conventions. below I will sort out some rules and then take some notes, I hope the article will help you.

Naming rules

Class files are all suffixed with. class. php. They are named by the camper method and capitalized, for example, Pay. class. php;

The class name and the Directory _ file name are consistent. For example, the Directory of the class name Zend_Autoloader is Zend/Autoloader. class. php;

The function name can be lowercase letters or underscores. Example: get_client_ip;

The method naming method uses the hump method, the first letter is lowercase or the underline "_", for example, listComment (), _ getResource (). Generally, the method starting with an underscore is a private method;

Attribute naming uses the camper method. The first letter is lowercase or the underline "_", for example, $ username, $ _ instance. generally, attributes starting with an underscore are private attributes;

Constants are named by uppercase letters and underscores (_), such as "HOME_URL ";

Common terms

1> list nouns (singular), such as listApple, read the Apple list at first glance. We do not need to write them as getApples, listApples, or readApples-because get is generally used to read a single data, for example, getApple. listApples does not add s. We also know that the Apple list is used (ensure that the variable name is shortened as much as possible );

2> get nouns (singular );

3> The term "Total" indicates the Total number of items. Such as expenseTotal;

4> found: indicates whether a value has been found;

5> uccess or OK: whether an operation is successful;

6> done: whether a project is completed;

7> error: indicates whether an error has occurred;

8> result: returned results

Code reconstruction

1. the code in the function or method body should be controlled on a screen as much as possible.

2. random deletion of unused methods in the class.

3. modify the methods in others' classes and sign them.

4. write a readme file in each module (for complex business instructions or code instructions ).

5. try to make every class do its own thing, and every function does one thing.

The following are some additional methods:

I. file format

1. for files that only contain php code, will we ignore them at the end of the file?> . This is to prevent extra spaces or other characters from affecting the code.

For example, the following code:

2. indentation should be able to reflect the logic results of the code. try to use four spaces and do not use TAB tabs, because this ensures the flexibility of cross-client programming software. For example:

If (1 ==$ x ){

$ Indented_code = 1;

If (1 = $ new_line ){

$ More_indented_code = 1;

}

}

3. variable values must be given equal spacing and arrangement. For example:

$ Variable = 'demo'; $ var = 'demo2 ';

4. the length of each line of code should be limited to 80 characters, up to 120 characters. Because linux reads files in the unit of 80 columns, that is to say, if a line of code contains more than 80 characters, the system will pay additional operation instructions for this. Although this seems to be a small problem, it is also a noteworthy and compliant standard for programmers pursuing perfection.

5. no extra spaces are allowed at the end of each line.

II. naming conventions

1. all class files are suffixed with. class. php, and the class file name can only contain letters. use the hump method and use uppercase letters, for example, DbMysql. class. php.

2. files other than the class library files such as configuration and functions are generally named ". inc. php "and ". php "is a suffix, and the name of the file name is named by lowercase letters and underscores. multiple words are separated by an underscore (_), for example, config. inc. php, common. php and install_function.php.

3. ensure that the file name is the same as the call case, because it is case sensitive on Unix-like systems.

4. the class name and file name are the same (including the same case), and only letters are allowed for the class name. for example, the file name of the UserAction class is UserAction. class. the file name of the php and InfoModel classes is InfoModel. class. php.

5. the controller class is suffixed with Action, such as UserAction and InfoAction. The Model class is suffixed with Model, such as UserModel and InfoModel. other classes are also suffixed with corresponding categories, such as Service and Widget.

6. the method name can only consist of letters, underlines are not allowed, the first letter must be lowercase, and then the first letter of each word must be capitalized, that is, the so-called "camper naming" rule, the more detailed the method, the better. you should be able to clearly describe the functions of this method, such as switchModel and findPage.

7. the name of an attribute can only consist of letters, underlines are not allowed, the first letter must be lowercase, and then the first letter of each word must be capitalized, that is, the so-called "camper naming" rule, for example, tablePrefix and tableName.

8. for access to object members, we must always use the "get" and "set" methods, for example:

class Foo { protected $_testObj; public function getTestObj() { return $this->_testObj; } public function setTestObj($testObj) { $this->testObj = $_testObj; } }

9. when the class member method is declared as private, it must start with a double underscore _; when it is declared as protected, it must start with a single underscore; generally, the method does not contain underscores, for example:

class Foo { private function __example() { // ... } protected function _example() { // ... } public function example() { // ... } }

10. if we need to define some frequently used methods as global functions, we should define them in the class in the form of static (static), for example:

class Think { // ... static public function autoload($classname) { // ... } }

11. the attribute of a class member declared as private must begin with a double underscore _; the attribute of a class member declared as protected must begin with an underscore; the member attribute declared as public cannot contain underscores at any time.

12. the function name should be in the lower-case letter and underline mode, and the more detailed the better, you should be able to clearly describe the function, such as get_client_ip.

13. when a method or function parameter does not need to be assigned a value, use null instead of false as the default value of the function parameter unless the parameter is a boolean value.

14. variables can only consist of lower-case letters and underscores. it is recommended that you use descriptive variables. the more detailed the variable, the better, so that $ I or $ n is not encouraged.

15. the constant and define constants in the global range in the class can only consist of uppercase letters and underscores. each word is separated by an underscore.

16. both boolean and null values are in lower case.

III. encoding style

1. php code must be bounded in the complete form ( ), That is, do not use php short labels ( .

2. when a string is composed of plain text (that is, it does not contain variables), it must always use single quotation marks (') as the delimiter. Example: $ a = 'example string ';

3. variables in variable replacement can only be in the form of $ + variable names. for example:

$ Greeting = Hello $ name, welcome back !; // $ Greeting = Hello {$ name} and welcome back are allowed !; // Allow $ greeting = Hello $ {name}, welcome back !; // Not allowed

When the dot number is used. when connecting each string, the string and the DOT must be separated by a space and can be divided into multiple lines to enhance readability. in this case, the dot. must be aligned with equal sign =, for example:

$sql = SELECT `id`, `name`  .  FROM `people`    . WHERE `name` = 'Susan'    . ORDER BY `name` ASC ;

When an array is constructed with an array symbol, a space must be added after each comma to enhance readability. for example: $ sampleArray = array (1, 2, 3, 'Think ', 'sns ');

4. when the array type operator is used to declare the associated array, we encourage it to be divided into multiple rows, but we must ensure the alignment of the keys and values of each row at the same time to keep the appearance, for example:

$sampleArray = array( 'firstKey'  => 'firstValue', 'secondKey' => 'secondValue' );


5. the start of braces must be in the top of the next line of the class name. for example:

class Think { // ... }

6. all code in the class must be indented with four spaces.

7. only one class can be declared in each php file. Writing other code in a class file is allowed, but this is not encouraged. If code is to be appended, it must be separated by blank lines.

8. the declaration of any class variable must be placed on the top of the class, prior to the declaration of any function.

9. variables cannot be declared using the var symbol. class member variables must be declared using private, protected, and public. Second, although it is allowed to declare the class members as public and directly reference them, it is usually better to use the get and set methods to declare class members.

10. the method must always use private, protected, or public to declare its scope.

11. the static method should declare its scope and should not be declared as private, but should be protected or public. if you just don't want to inherit from the quilt class, you should use final to declare them.

12. The initial braces of a function or method should be at the top of the next line of the function declaration. for example:

function get_client_ip() { // …}

13. unnecessary spaces are not allowed between the function or method name and parameter brackets. for example:

function get_client_ip() { // …}

14. the reference can only be defined in function parameters. it is forbidden to pass the reference in real time. for example:

// Reference definition in function parameters-allowed function defineRefInMethod (& $ a) {$ a = 'a';} defineRefInMethod ($ B); echo $ B; // 'A' // pass the reference in real time-the function callTimePassRef ($ a) {$ a = 'a';} callTimePassRef (& $ c); echo $ c; // 'A'

15. the function or method return value cannot be enclosed in parentheses. Otherwise, the readability will be reduced. if the function is changed to return reference, an exception will be thrown.

16. try to use the type prompts, especially in the module design. for example:

class Foo { public function foo(SomeInterface $object)    {  } public function bar(array $options) { } }

17. function and method parameters must be separated by commas (,) and spaces.

18. for functions whose parameters are arrays, the arrays in the parameters should be divided into multiple rows to enhance readability. for example:

ThreeArguments (array (1, 2, 3), 2, 3 );

ThreeArguments (array (1, 2, 3, 'Think', 'sns ', $ a, $ B, $ c, 56.44, $ d, 500), 2, 3 );

19. in condition control based on if, else, and else if, we must use spaces to separate the statement and brackets. the start of braces {must be in the same line as the condition control statement, end} always exclusive one row and the top level. the control process content must be indented with four spaces, and elseif is not used.

if ($condition) { // ... } else if ($_condition) { // ... } else { // ... }

20. in the condition brackets of the condition control statement, the operator must be separated by spaces from other elements. if a long logical judgment occurs, embedding brackets is encouraged to separate each logic. for example:

if (($a != 2) and ($b == 1)) { $a = $b; }

21. in the switch condition control statement, the parameters to be tested must be separated by spaces from other elements. for example:

switch ($num) { // …}

22. the content of the switch statement must be indented by four spaces, and the content controlled by the case condition must be indented by four spaces. for example:

Switch ($ indentedSpaces) {case 2: echo error; break; case 4: echo correct; break; default: break;} 23. the switch statement should always contain default control. 24. sometimes we need to omit the break or return in the case context. in this case, we must add // no break comment for these case statements. for example: switch ($ numPeople) {case 1: // here there is no break case 2: break; default: break ;}


Permanent link:

Reprint at will! Include the article address.

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.