PHP 8 新特性
PHP 8 新特性 命名参数(8.0) 新增命名参数的功能: 在函数或方法调用时,可通过参数名来指定参数的值,而不仅仅依赖参数的位置 从 PHP 8.0.0 开始,函数参数列表可以包含一个尾部的逗号,这个逗号将被忽略。这在参数列表较长或包含较长的变量名的情况下特别有用,这样可以方便地垂直列出参数。 <?php function takes_many_args( $first_arg, $second_arg, $again = 'a default string', // 在 8.0.0 之前,这个尾部的逗号是不允许的。 ){ // ... } z takes_many_args(1, 2); //按照参数顺序传参 takes_many_args(first_arg:1, second_arg:2); //指定参数,不分顺序 // 类也可以使用命名参数,假设Demo类构造函数有$first_arg,$second_arg,两个参数,有takes_many_args方法 $demo = new Demo(first_arg:1, second_arg:2); $demo->takes_many_args(first_arg:1, second_arg:2); // 不能用位置的参数和命名的参数一起 // 可选参数必须在必选参数后面 例如上面的$again ?> 注解(Attributes)(8.0) 新增注解的功能。 此篇单独介绍 构造器属性提升(Constructor Property Promotion)(8.0) 新增构造器属性提升功能 在构造函数中声明类的属性)。 构造器的参数也可以相应提升为类的属性。 构造器的参数赋值给类属性的行为很普遍,否则无法操作。 而构造器提升的功能则为这种场景提供了便利。 <?php class Point { protected int $x; protected int $y; public function __construct(int $x, int $y = 0) { $this->x = $x; $this->y = $y; } } // 两个参数都传入 $p1 = new Point(4, 5); // 仅传入必填的参数。 $y 会默认取值 0。 $p2 = new Point(4); // 使用命名参数(PHP 8....