编写 PHP 代码更优雅些 - 持续更新 作者: Chuwen 时间: 2021-09-05 分类: PHP技巧,PHP ### 基础 PHP 8.0 + #### 命名参数 ```php // PHP 7 htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false); // PHP 8 htmlspecialchars($string, double_encode: false); ``` ### 注解 > 现在可以用 PHP 原生语法来使用结构化的元数据,而非 PHPDoc 声明。 ```php // PHP 7 class PostsController { /** * @Route("/api/posts/{id}", methods={"GET"}) */ public function get($id) { /* ... */ } } // PHP 8 class PostsController { #[Route("/api/posts/{id}", methods: ["GET"])] public function get($id) { /* ... */ } } ``` #### 构造器属性提升 ```php // PHP 7 class Point { public float $x; public float $y; public float $z; public function __construct( float $x = 0.0, float $y = 0.0, float $z = 0.0 ) { $this->x = $x; $this->y = $y; $this->z = $z; } } // PHP 8 class Point { public function __construct( public float $x = 0.0, public float $y = 0.0, public float $z = 0.0, ) {} } ``` #### 联合类型 > 相较于以前的 PHPDoc 声明类型的组合, 现在可以用原生支持的联合类型声明取而代之,并在运行时得到校验。 ```php // PHP 7 class Number { /** @var int|float */ private $number; /** * @param float|int $number */ public function __construct($number) { $this->number = $number; } } new Number('NaN'); // Ok // PHP 8 class Number { public function __construct( private int|float $number ) {} } new Number('NaN'); // TypeError ``` #### Match 表达式 ```php // PHP 7 switch (8.0) { case '8.0': $result = "Oh no!"; break; case 8.0: $result = "This is what I expected"; break; } echo $result; //> Oh no! // PHP 8 echo match (8.0) { '8.0' => "Oh no!", 8.0 => "This is what I expected", }; //> This is what I expected ``` #### Nullsafe 运算符 ```php // PHP 7 $country = null; if ($session !== null) { $user = $session->user; if ($user !== null) { $address = $user->getAddress(); if ($address !== null) { $country = $address->country; } } } // PHP 8 $country = $session?->user?->getAddress()?->country; ``` ---- ### 枚举 1. 使用 PHP 8.1,截止到 2021年9月4日,8.1 版本未正式发布 2. 使用扩展包实现:https://github.com/myclabs/php-enum ```shell composer require myclabs/php-enum ``` ### JSON 转 Class 使得 IDEA 语法提示 > Github: https://github.com/cweiske/jsonmapper ```shell composer require netresearch/jsonmapper ``` ### 泛型 https://github.com/mrsuh/php-generics 标签: PHP