PHP8 新特性解读和示例

PHP技术
440
0
0
2022-07-30
标签   PHP8

PHP8.0 新特性解读和示例

新增命名参数功能
啥是命名参数?
就是 具名 参数,在调用函数的时候,可以指定参数名称,指定参数名称后,参数顺序可以不安装原函数参数顺序传.
例子:
  <?php 
      /**
       * 计算余额方法
       * @param $amount 账户金额
       * @param $payment 支出金额
       * @return $balance = $amount-$payment 余额
       */ 
      function balance($amount, $payment)
      {
          return $amount - $payment;
      }
      //传统方式调用 
      balance(100, 20);
      //php8 使用命名参数调用 
      balance(amount: 100, payment: 20);
      //也可以换个顺序,这样来 
      balance(payment: 20, amount: 100);
注解功能
啥是注解?直接上代码,最后在解释
例子:
#[Attribute]
class PrintSomeThing
{
  public function __construct($str = '')
  {
     echo sprintf("打印字符串 %s \n", $str);
  }
}
#[PrintSomeThing("hello world")]
class AnotherThing{}
// 使用反射读取注解
$reflectionClass = new ReflectionClass(AnotherThing::class);
$attributes = $reflectionClass->getAttributes();
foreach($attributes as $attribute) {
  $attribute->newInstance(); //获取注解实例的时候,会输出 ‘打印字符串 Hello world’
}
注解功能个人理解总结,使用注解可以将类定义成一个一个 低耦合,高内聚 的元数据类。在使用的时候通过注解灵活引入,反射注解类实例的时候达到调用的目的。
**注解类只有在被实例化的时候才会调用
构造器属性提升
啥意思呢,就是在构造函数中可以声明类属性的修饰词作用域
例子:
<?php 
    // php8之前 
    class User
    {
        protected string $name;
        protected int $age;
        public function __construct(string $name, int $age)
        {
            $this->name = $name;
            $this->age = $age;
        }
    }
    //php8写法, 
    class User
    {
        public function __construct(
            protected string $name,
            protected int $age
        ) {}
    }
节约了代码量,不用单独声明类属性了。
联合类型
在不确定参数类型的场景下,可以使用.
例子:
    function printSomeThing(string|int $value)
    {
        var_dump($value);
    }
Match表达式
和switch case差不多,不过是严格===匹配
例子:
<?php
$key = 'b';
$str = match($key) {
    'a' => 'this a',
    'c' => 'this c',
     0  => 'this 0',
    'b' => 'last b',
};
echo $str;//输出 last b
新增 Nullsafe 运算符
<?php 
   class User
   {
       public function __construct(private string $name)
       {
           //啥也不干
       }
       public function getName()
       {
           return $this->name;
       }
    }
    //不实例 User 类,设置为null 
    $user = null;
   echo $user->getName();//php8之前调用,报错 
   echo $user?->getName();//php8调用,不报错,返回空
简化了 is_null 判断