php8新特性
1.php8新特性
- 命名参数
1 <?php 2 function foo($a, $b, $c = 3, $d = 4) { 3 return $a + $b + $c + $d; 4 } 5 //d:40就是命名参数,命名参数可以任意位置传递,但不可重复 6 var_dump(foo(...[1, 2], d: 40)); // 46 7 var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46 8 9 var_dump(foo(...[1, 2], b: 20)); // Fatal error。命名参数 $b 覆盖之前的参数 10 ?>
- 注解:注解功能提供了代码中的声明部分都可以添加结构化、机器可读的元数据的能力, 注解的目标可以是类、方法、函数、参数、属性、类常量。 通过 反射 API 可在运行时获取注解所定义的元数据。 因此注解可以成为直接嵌入代码的配置式语言。(参考hyperf)
- 构造器属性提升
1 <?php 2 class Point { 3 public function __construct(protected int $x, protected int $y = 0) { 4 } 5 }
- 联合类型
1 <?php 2 function x(int|string $param):int|string{ 3 }
- match 表达式: 用于替换if_else语句
<?php $res = match($num){ 1 => "one", 2 => "two", 3,4,5 => "3,4,5", "2" => 2 } $res = match($num){ $num < 0 => "-", $num > 0 => "+" } //在匹配数组时要数组顺序一致 $res = match($array){ ["type" => 1 "name" => 1] => "s" }
- nullsafe 运算符 “?->”, 如果链条上一个失败了就返回null
1 $count = $user?->order?->count;
- 字符串和数字比较更新:数字字符串会按照字符串比较,非数字字符串会把数字转为字符串比较。
//php8 0 == "foo"; 失败会报错 //php7 0 == "foo" true
- 枚举类 enum
1 enum color { 2 case red; 3 case green; 4 case x = “x”; 5 } 6 7 print(color::red->name); 8 print(color::red->value); 9 print(color::tryFrom("z"));//有z就返回值,没有返回null 10 eunm_exists("color") //类是否存在
- 只读类型 readonly
1 //只读属性只能在对象被创建时通过构造函数初始化。一旦设置,它们就不能被更改 2 class Person { 3 public function __construct(private readonly string $name) { 4 } 5 6 public function getName(): string { 7 return $this->name; 8 } 9 } 10 11 $person = new Person("Alice"); 12 echo $person->getName(); // 输出: Alice
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架