PHP documentation on coding standards (collection)

黄舟
Release: 2023-03-14 09:44:01
Original
1764 people have browsed it

In order to improve work efficiency, ensure the effectiveness and rationality of development, maximize the readability and reusability of program code, and improve communication efficiency, a code writing specification is required. Let everyone develop good coding habits and reduce bugs in the code.
CleverCode has compiled some specifications. This specification includes naming conventions, code indentation rules, control structures, function calls, function definitions, comments, included codes, PHP tags, and common naming rules in program coding during PHP development.

1 File format

1.1 File tag

All PHP files use complete PHP tags for their code tags. It is not recommended to use short tags, such as:

<?php  
//推荐  
echo &#39;hello world&#39;;  
?>  
  
  
<?  
//短标签格式不推荐  
echo &#39; hello world &#39;;  
?>
Copy after login

1) Using short tag format is easy to be confused with XML, and not all PHP versions and servers support or turn on the short tag option by default (starting from PHP5.4, the short tag option in php.ini does not affect the use of short tags) . For files containing only PHP code, the ?> at the end of the file will be ignored. This is to prevent extra spaces or other characters from affecting the code.
2) In fact, this problem only occurs when compression or caching output is not enabled, for example:
php.ini-Disable compressed output and cached output

zlib.output_conpression = off
output_buffering = off
Copy after login

foo.php , note that there are some spaces or line breaks behind this time, of course this is not visible on the page.

<?php  
    $foo= &#39;foo&#39;;  
?>
Copy after login

index.php, while including foo.php, actually outputs some spaces or newlines.


<?php  
    include &#39;foo.php&#39;;  
    session_start();  
?>
Copy after login

You will see a warning: "...Cannotsendsessioncachelimiter-headersalreadysent..."


1.2 File and directory naming

Program file names and directory names are all named in meaningful English. Do not use pinyin or meaningless letters. Only letters, numbers, underline and underline characters are allowed, and must end with ".php" (template except documents).

//Classes are unified using
DemoTest.php


2 Naming convention

2.1 Variable naming

Variables in PHP use a The dollar sign is followed by the variable name. Variable names are case-sensitive. A valid morph name begins with a letter or an underscore, followed by any number of letters, numbers, or underscores. Normal

regular expression will be expressed as: [a-zA-Z_\x7f-\xff][a-zA-ZO-9_'x7f-\xff], Chinese characters etc. should not be used in variables Non-ASCII characters.

2.1.1 The entire program

The entire program is named in camel case, starting with a lowercase letter, and the name must be meaningful, such as:

function displayName($name){  
    echo $name;  
}
Copy after login

2.1.2 PHP global variables Key value

PHP global variable key value has a middle on both sides and is named using camel case.

2.1.3 Ordinary variables

Ordinary variables adopt the camel case method as a whole,

name according to convention, and avoid using common keywords or words with ambiguous meanings. Variables should be noun-based.
String:$myName
Array:$myArray

Not recommended:
$yes: It should not be used as a bool variable because the variable is likely to be changed, which may cause Syeszflase, making its code logic confusing.
$sex: An English word with vague meaning and unauthenticity. The name of gender should be $gender.

2.1.4 Function name

The function name should be meaningful so that you know what it is going to do at a glance, and it should also be abbreviated as much as possible. It is recommended to use a naming method of verb or verb plus adjective

, such as showMsg. It is not recommended to use the following function name:

getPublishedAdvertisementBy
CategoryAndCategoryldAndPosition()
Copy after login

The above function name can be refined to:

getAd($category,$categoryid,$position,$published)
Copy after login

For example 1) Class public function:


public function doGetUserName($job)
Copy after login

For example 2) Class private functions, starting with "_":


private function _doGetUserName($job)
Copy after login

For example 3) Class protected functions, starting with "_":

protected function _doGetUserName($job)
Copy after login

2.1.5 Class Attributes in

Variables in the class follow the naming rules of ordinary variables.

For example 1) public attributes, static attributes:

public $userName = ’CleverCode’;
static $userType = array(1,2,3);
Copy after login

For example 2) private attributes, starting with "_":


private $_userName = ’CleverCode’;
Copy after login

For example 3) protected attributes, Starting with "_":


protected $_userName = ’CleverCode’;
Copy after login

For example 4) Constants, all uppercase, separated by "_":


const TYPE_GZ = 4;
Copy after login

2.2 Database naming

2.2 .1 Library naming

1) Use lowercase letters. (Windows is not case-sensitive, Linux is case-sensitive, so all lowercase is for library porting compatibility)

2) It consists of multiple words, separated by "_".
For example:

db_user,db_system。
Copy after login

2.2.2 Table naming

1) Table names all use lowercase letters.

2) The table name uses a unified prefix, and the prefix cannot be empty (modular, and can effectively avoid MYSQL reserved words).
3) For table names composed of multiple words, use "_" intervals.
For example:

pre_users,pre_user_shop
Copy after login

2.2.3 Table field naming

1)全部使用小写字母命名。
2)多个单词不用下画线进行分割(重要)。
3)如果有必要,给常用字段加上表名首字母作为前缀。
4)避免使用关键字和保留字,但约定俗成的除外。
例如:

username,newsid,userid,logid
Copy after login

3 注释规范

3.1 文件注释

文件注释通常放在整个PHP文件头部,其内容包括文件版权、作者、编写日期、版本号等
重要信息。PHP中,可以参照phpdocument规范,便于利用程序自动生成文档。
文件注释遵循以下规则:
1)必须包含本程序的描述;
2)必须包含作者;
3)必须包含版权;
4)必须包含文件的名称;
5)可以包含书写日期;
6)可以包含版本信息;
7)可以包含重要的使用说明,如类的调用方法、注意事项等。
例如:

<?php  
  
  
/**  
 * SystemUser.php  
 *   
 * 系统用户操作操作  
 *  
 * Copyright (c) 2015 http://blog.csdn.net/CleverCode  
 *  
 * modification history:  
 * --------------------  
 * 2015/5/11, by Clever Code, Create  
 *
Copy after login

3.2 类与接口注释

类和接口的注释应该尽量简洁。按照一般的习惯,一个文件只包含一个类,在类注释中通常不需要再加上作者和版本等信息,加上可见性和简中的描述即可。如果文件注释已经足够详细,可以不用给类写注释。如果同时存在接口和接口的实现类,通常做法是仅在接口中进行注释。

3.3 方法和函数注释

方法和函数的注释写在前面,通常需要标明的信息主要是可见性、参数类型和返回值的类
例如1:

/** 
  * 对比新旧数据 
  * 
  * @param bigint $userid 人编号 
  * @param array $oldMap 旧数据 
  * @param array $newMap 新数据(输出参数) 
  * @return string 成功返回&#39;OK&#39;,失败返回错误信息 
  */  
 public static function diffRecommendInfo($userid, $oldMap, &$newMap){  
 }
Copy after login

例如2:

/** 
  * 插入日志数据 
  * 
  * @param bigint $data[‘userid’] 用户编号 
  * @param array $data[‘logintime’] 登录时间 
  * @return string 成功返回&#39;OK&#39;,失败返回错误信息 
  */  
 public static function insertLogData($data){  
 }
Copy after login

3.4 Action注释

由于我们都是使用的zend开发模式,在Action是http请求处理逻辑的入口,那么必然会传递get,post等参数。可以注释如下.
例如1)没有get,post传递参数时候:

/** 
     * 自动设置名称 
     * 
     * @return void 
     */  
    public function autosetAction(){  
}
Copy after login

例如2 )有get传递参数时候:

/** 
     * 获取用户名称 
     * 
     * @get int $userid 用户编号 
     * @get int $currpage 当前页 
     * @get int $pagesize 
     * 
     * @return void 
     */  
public function getusernameAction(){  
}
Copy after login

例如3) 有post传递参数时候:

/** 
     * 删除用户 
     * 
     * @post int $userid 用户编号 
     * @return void 
     */  
public function deleteuserAction(){  
}
Copy after login

3.5 单行注释

1)写在被注释代码前面,而不是后面。但对于单行语句,按照习惯可以把注释放在语句末尾,也可以写在行上面。
2)对于大段注释,使用/**/格式,通常在文件和函数注释中使用,而代码内部统一使用//注释,因为其写起来简单。
例如:
//姓名

$name = ’CleverCode’;

4 代码风格

4.1 缩进与空格

在书写代码的时候,必须注意代码的缩进规则:
1)使用4个空格作为缩进,而不使用tab缩进(如在UltraEdit中可以进行预先设置)。
2)变量赋值时,等号左右留出空格。
例如:
$name = 'CleverCode';//推荐
$name='CleverCode';//不推荐

为了最大程度减轻工作量,保持代码美观,建议使用大型IDE管理代码。比如,在zend studio中,使用Ctrl+Shift+F组合键对代码进行格式化。

4.2 语句断行

代码书写中应遵循以下原则:
1)尽量保证程序语句一行就是一句;
2)尽量不要使一行的代码太长,一般控制在80个字符以内;
如果一行代码太长,请使用类似.=的方式断行书写;
执行数据库的SQL语句操作时,尽量不要在函数内写SQL语句,而先用变量定义SQL
语句,然后在执行操作的函数中调用定义的变量。
例如:

//代码分割
$sql= "SELECTusername,password,address,age,postcode from test_t";
$sql.= "WHEREusername=${user}";
$ret = mysql_query($sql);
Copy after login

3)一个函数控制在200行以内;
4)if最多嵌套3层;
//不推荐

If(){  
    If(){  
        If(){  
            If(){  
                ……  
            }  
        }  
    }  
}
Copy after login

5)循环最多3层。

//不推荐  
For(){  
    For(){  
        For(){  
            For(){  
                ……  
            }  
        }  
    }  
}
Copy after login

6)if或者for语句块中只有一行时候,加上{}。当有语句变动的时候会带来不必要的bug。

//推荐  
If($a == 1){  
    echo 1;  
}  
  
//不推荐  
If($a == 1) echo 1;
Copy after login

4.3 空行

1)函数与函数之间空行。
2)同一个函数不同逻辑块之间空行,查阅不同的逻辑块条理更清晰。


4.4 函数结构

通常一个函数分为三部分。第一部分:检查参数;第二部分:处理逻辑;第三部分:返回结果。
例如:

/** 
 * 删除日志通过uid 
 * 
 * @param string $uid 用户uid 
 * @return string 成功返回&#39;OK&#39;,失败返回错误信息 
 */  
public static function deleteLogByUid($uid){  
  
  
    //第一步:检查参数。防止处理部分异常;比如$uid是传入array();  
    if (!is_numeric($uid)) {  
        return &#39;!is_numeric($uid)&#39;;  
    }  
      
    //第二步:处理逻辑。  
    $affected = $userLogTable->delete(&#39;where userid = &#39; . $uid);  
      
    //第三步:返回结果。让调用者知道是否处理正常。  
    if($affected){  
        return &#39;OK&#39;;  
    }  
      
    return &#39;delete error!&#39;;  
}
Copy after login

4.5 函数返回函数

需要客户端的函数:
返回值

$ret = array(‘code’=> 1 ,msg=>’’,data => array());
Copy after login

4.6 更好的习惯

在代码中,使用下面列举的写法,可以使代码更优雅。
1)多使用PHP中已经存在的常量,而不要自己定义,例如:

echo$meg."\r\n";
echo$msg,PHPJEOL;
Copy after login

PHP中,PHP_EOL是一个预定义常量,表示一行结束,随着所使用系统的不同,使用PHP_EOL会让代码更具有可移植性。

2)更详尽的注释。
注释是一门艺术,好的注释可以比代码更精彩。不用担心效率问题。一则注释对代码的效
率影响不大,其次在正式产品中可以对代码中的注释进行批量删除。注释做到极致和完美的典型代表是Apache组织各种产品的源代码。

3)不要滥用语法糖。
语法糖也就是语言中的潜规则,即不具有普遍代表性的语法。少量使用语法糖会尝到甜
头,大量使用则是一种灾难。
例如以下代码,可读性比较差;

$a?$a-$b:3&&$c&&$d=1;
Copy after login

The above is the detailed content of PHP documentation on coding standards (collection). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!