Home  >  Article  >  php教程  >  PHP编程之代码命名规范

PHP编程之代码命名规范

WBOY
WBOYOriginal
2016-05-25 16:45:441409browse

文件名:一律小写,单词间以下划线分隔

类名:采用首字母大写的驼峰命名方式

类中的方法名:采用首字母小写的驼峰方式命名

类中的私有方法和私有变量:以下划线开头

函数名(变量名):全小写,单词间以下划线分隔

下面具体介绍

Θ 类文件都以.class.php为后缀,使用驼峰法命名,并且首字母大写,例如 Pay.class.php;

Θ 类名和目录_文件名一致。例如:类名Zend_Autoloader的目录是Zend/Autoloader.class.php;

Θ 函数的命名使用小写字母和下划线的方式。例如:get_client_ip;

Θ 方法的命名使用驼峰法,首字母小写或者使用下划线"_",例如listComment(),_getResource(),通常下划线开头的方法属于私有方法;

Θ 属性的命名使用驼峰法,首字母小写或者使用下划线"_",如$username,$_instance,通常下划线开头的属性属于私有属性;

Θ 常量以大写字母和下划线"_"命名,如"HOME_URL";

理解一下消化一下:

1.缩进及行的长度

缩进4个空格,而不是tab(有些编辑器可以配置一个tab代表多个空格,注意是空格),每行保持大约75-85个字符的长度.

2.控制结构

这个部分最容易忽略,也是影响代码美感最重要的方面,例子很详细了,受益匪浅,代码如下:

<?php
if ((condition1) || (condition2)) {
    action1;
} elseif ((condition3) && (condition4)) {
    action2;
} else {
    defaultaction;
}
?>
<?php
switch (condition) {
    case 1:
        action1;
        break;
    case 2:
        action2;
        break;
    default:
        defaultaction;
        break;
}
?>
<?php
if (($condition1 || $condition2) && $condition3 && $condition4) {
    //code here
    
}
?>
<?php
$a = $condition1 && $condition2 ? $foo : $bar;
$b = $condition3 && $condition4 ? $foo_man_this_is_too_long_what_should_i_do : $bar;
?>

3.函数调用,代码如下:

<?php
$var = foo($bar, $baz, $quux);
$short = foo($bar);
$long_variable = foo($baz);
?>

4.类名规范,代码如下:

<?php
class Foo_Bar {
    //... code goes here
    
}
?>

5.方法名规范(驼峰命名),代码如下:

<?php
function fooFunction($arg1, $arg2 = &#39;&#39;) {
    if (condition) {
        statement;
    }
    return $val;
}
?>

6.数组定义规范,代码如下:

<?php
$some_array = array(
    &#39;foo&#39; => &#39;bar&#39;,
    &#39;spam&#39; => &#39;ham&#39;,
);
?>

7.注释

http://pear.php.net/manual/en/standards.sample.php

http://pear.php.net/manual/en/standards.header.php

8.Including Code

任何时候都应该采用include_once或者require_once

require_once 'foo.php';


Statement:
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