php8新特性

  1. 命名参数
     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 ?>
  2. 注解:注解功能提供了代码中的声明部分都可以添加结构化、机器可读的元数据的能力, 注解的目标可以是类、方法、函数、参数、属性、类常量。 通过 反射 API 可在运行时获取注解所定义的元数据。 因此注解可以成为直接嵌入代码的配置式语言。(参考hyperf)
  3. 构造器属性提升
    1 <?php
    2 class Point {
    3     public function __construct(protected int $x, protected int $y = 0) {
    4     }
    5 }
  4. 联合类型
    1 <?php
    2 function x(int|string $param):int|string{
    3 }
  5. 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"  
    }
  6. nullsafe 运算符 “?->”, 如果链条上一个失败了就返回null
    1 $count = $user?->order?->count
  7. 字符串和数字比较更新:数字字符串会按照字符串比较,非数字字符串会把数字转为字符串比较。
    //php8
    0 == "foo"; 失败会报错
    //php7
    0 == "foo" true
  8. 枚举类 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") //类是否存在

     

  9. 只读类型 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

     

posted @ 2024-04-22 00:39  yueSAMA  阅读(4)  评论(0编辑  收藏  举报