PHP代码规范

By admin, 27 十一月, 2015
  1. 文件统一使用UTF-8编码
  2. 类名使用StudlyCaps风格
  3. 方法名使用camelCase风格
  4. 常量名使用CONSTANT_VARIABLE风格
  5. 属性名、变量名建议使用以下三种风格之一:$StudlyCaps, $camelCase, or $under_score。在一定作用域范围内,这种风格应该是一致的。
  6. 使用空格做缩进,而不是TAB。编辑器可以设置把TAB转换成空格。
  7. 行的长度应尽量保持在80个字符以内,不应超过120字符。编辑器可以在80个字符处设置一条竖线。
  8. 左圆括号后、右圆括号前不应有空格。例如:if ($a === $b) 不应写成if ( $a === $b )
  9. 赋值、运算符号两边应该有空格,但++除外。例如:for ($i = 0; $i < 10; $i++)
  10. 适当的地方加空行把代码按逻辑归类

 

代码风格示例:

<?php
namespace Vendor\Package;

use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class Foo extends Bar implements FooInterface
{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }

    final public static function bar()
    {
        // method body
    }
}

总结:我没有能找到一份我满意的代码规范,至少我自己不愿意完全按照某一个规范去做。我很希望见到有规范说注释符号//后面应该有一个空格(我在C++规范里见过),但是很遗憾没有。包括运算符号两边应该有空格的规范也是没有见到。由于没有这样的业界规范存在,我只能忍受员工写的那些丑陋的代码。“忍”是患有强迫症的处女座应该铭记的品质。

 

参考:

 

标签

评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"