class PostsController { /** * @Route("/api/posts/{id}", methods={"GET"}) */ public function get($id) { /* ... */ } }
在PHP8中,注解写法优化为:
class PostsController { #[Route("/api/posts/{id}", methods: ["GET"])] public function get($id) { /* ... */ } }
现在可以用 PHP 原生语法来使用结构化的元数据,而非 PHPDoc 声明。
构造器属性提升
在PHP7中,构造器的写法为:
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; } }
在PHP8中,构造器的写法优化为:
class Point { public function __construct( public float $x = 0.0, public float $y = 0.0, public float $z = 0.0, ) {} }
现在可以用更少的样板代码来定义并初始化属性。
联合类型
在PHP7中,联合类型的写法为:
class Number { /** @var int|float */ private $number; /** * @param float|int $number */ public function __construct($number) { $this->number = $number; } } new Number('NaN'); // Ok
在PHP8中,联合类型的写法优化为:
class Number { public function __construct( private int|float $number ) {} } new Number('NaN'); // TypeError
strlen([]); // Warning: strlen() expects parameter 1 to be string, array given array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0
在PHP8中对此进行了优化:
strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0