输写更规范的php代码 – psr-2

Overview

For example:

<?php
namespace Vendor\Package;

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

class Foo extends Bar implements FooInterface
{
    public function sampleMethod($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
    }
}

额外

Files

Lines

Indenting

Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.代码必须使用4个空格符的缩进,一定不能用 tab键。

N.b.: Using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations. The use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment.

备注: 使用空格而不是tab键缩进的好处在于,避免在比较代码差异、打补丁、重阅代码以及注释时产生混淆。并且,使用空格缩进,让对齐变得更方便。

Keywords and True/False/Null

PHP keywords MUST be in lower case.

The PHP constants true, false, and null MUST be in lower case.

Classes, Properties, and Methods

当implements一行放不下时时,建议如下写法

<?php
namespace Vendor\Package;

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

class ClassName extends ParentClass implements
    \ArrayAccess,
    \Countable,
    \Serializable
{
    // constants, properties, methods
}

常规写法

<?php
namespace Vendor\Package;

class ClassName
{
    public function fooBarBaz($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}

Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.

方法和类的时候{}的位置注意一下

<?php
namespace Vendor\Package;

class ClassName
{
    public function aVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {
        // method body
    }
}

常规方法调用

<?php
bar();
$foo->bar($arg1);
Foo::bar($arg2, $arg3);

参数过长时调用

$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);

Yoyo 「二是一种不三不四的态度」

男 1990.12.22 429660248@qq.com

发表评论

电子邮件地址不会被公开。 必填项已用*标注