php代码风格,PHP代码风格指南

PHP编码规范

PSR-2

概要

务必要遵循 PSR-1 规范;

4个空格缩进(编辑器设置下Tab键占4个空格即可);

每行字符不得超过120个,最好控制在80内;

声明namespace后空一行;

声明use后空一行,多个use之间不空行;

class与method的开始{与结束}括号必须独自占一行;

class的属性与方法可见性必须注明,且abstract 、final必须在public等一般可见性之前,static排最后。

控制结构中关键词如if后面必须有一个空格,而函数或者方法后面不能跟空格,如funName();

控制结构中的开始{与语句在同一行,而结束}须另起一行;

控制结构中的开始圆括号后不能有空格,结束圆括号之前也不能有空格。

Examples

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

}

}

namespace Vendor\Package;

use FooClass;

use BarClass as Bar;

use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements \ArrayAccess, \Countable

{

// constants, properties, methods

}

namespace Vendor\Package;

use FooClass;

use BarClass as Bar;

use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements

\ArrayAccess,

\Countable,

\Serializable

{

// constants, properties, methods

}

namespace Vendor\Package;

class ClassName

{

public $foo = null;

}

namespace Vendor\Package;

class ClassName

{

public function fooBarBaz($arg1, &$arg2, $arg3 = [])

{

// method body

}

// 参数较多的话可以这样:

public function aVeryLongMethodName(

ClassTypeHint $arg1,

&$arg2,

array $arg3 = []

) {

// method body

}

}

namespace Vendor\Package;

abstract class ClassName

{

protected static $foo;

abstract protected function zim();

final public static function bar()

{

// method body

}

}

if ($expr1) {

// if body

} elseif ($expr2) {

// elseif body

} else {

// else body;

}

switch ($expr) {

case 0:

echo 'First case, with a break';

break;

case 1:

echo 'Second case, which falls through';

// no break

case 2:

case 3:

case 4:

echo 'Third case, return instead of break';

return;

default:

echo 'Default case';

break;

}

while ($expr) {

// structure body

}

do {

// structure body;

} while ($expr);

for ($i = 0; $i < 10; $i++) {

// for body

}

foreach ($iterable as $key => $value) {

// foreach body

}

try {

// try body

} catch (FirstExceptionType $e) {

// catch body

} catch (OtherExceptionType $e) {

// catch body

}

有省略。详细参考 PSR-2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值