规则Rule
PHPDoc
- 变量以及属性的辅助注解.方便IDE跳转和追踪
<?php
$foo = 2 + 2;
final class Foo
{
public $bar;
public $baz;
}
- 变量以及属性多态类型优先级
- 注释对齐(居中非依左或不对齐)
/**
* @param EngineInterface $templating
* @param string $format
* @param int $code an HTTP response status code
* @param bool $debug
* @param mixed &$reference a parameter passed by reference
* @param EngineInterface $templating
* @param string $format
* @param int $code an HTTP response status code
* @param bool $debug
* @param mixed &$reference a parameter passed by reference
- 未确定类型使用
mixed
声明,默认值带为null需要用?
修饰符
function foo(?string = null $foo, int $bar, $baz) {}
- 数组key以及类属性对齐
class Foo
{
public $a = 0;
public $b = 0;
public $c = 0;
public$d = 0;
}
class Foo
{
public $a = 0;
public $b = 0;
public $c = 0;
public $d = 0;
}
$arr = [
'a'=>'tom',
'c' => 'sevne',
'd'=> 'mazda',
'b' =>'cross m78 unm',
]
$arr = [
'a' => 'tom',
'c' => 'sevne',
'd' => 'mazda',
'b' => 'cross m78 unm',
]
代码约束
- declare_strict 严格声明。主要解决程序在处理类型时候避免隐性转换
declare(strict_types=1);
- 使用常量
PHP_EOL
替代 "\n"
换行符号
echo "some thing \n";
echo "some thing PHP_EOL";
- 声明函数必须使用
function_exists
包裹判断,避免函数重复声明
if (!function_exists('dd')) {
function dd(...$vars)
{
foreach ($vars as $v) {
VarDumper::dump($v);
}
exit(1);
}
}
- 函数或类的方法没有返回类型需要声明
void
类型
function foo(string $a): void {}
class Foo
{
public function handle(): void;
{
}
}
- 命名空间导入,导入或完全限定全局类/函数/常量
<?php
$d = new \DateTimeImmutable();
$d = new DateTimeImmutable();
- 使用
::class
替换完整类名使用,以及替代get_class
函数
$className = 'Foo\Bar\Baz';
$className = Baz::class;
- 多次调用转换成单次调用
$a = isset($a) && isset($b);
$a = isset($a, $b) ;
unset($a);
unset($b);
unset($a, $b);
- 使用语法糖简化调用
$boo = isset($foo) ? $foo : null;
$boo = $foo ?? null;
$foo ??= null;
$boo = $foo ? $foo : '';
$boo = $foo ?:'';
list($a, $b) = $foos;
[$a, $b] = $foos;
- 变量占位符由
${
转换{$)
php的高版本已经抛弃${
用法
$name = 'World';
echo "Hello ${name}!";
echo "Hello {$name}!";
- PHP常量true、false和null须使用小写
$a = FALSE;
$b = True;
$c = NULL;
$a = false;
$b = true;
$c = null;
- 使用动态属性或方法,属性需要实现
__get
和__set
,方法需要_call()
或__callStatic
以及在class 头部声明,便于ide识别以及查阅
class Foo
{
public function __set($name, $value)
{
}
public function __get($name)
{
}
public function __call($method, $args)
{
}
public static function __callStatic($method, $args)
{
}
}
耦合优化
- 使用依赖对象处理多参数方法或函数,避免后面迭代出现超级函数
function foo(string $argv, int $argc, array $arg, \Closure $argz) :void
{
}
Class Boo
{
public string $argv;
public string $argc;
public string $argg;
public function argz() : Closure
{
return function (){ };
}
}
function foo(Boo $boo) :void
{
}