PHP8新特性

1 . JIT(Just In Time) 编译器

JIT提升了PHP运行性能,特别是在计算密集型场景(如图像处理,科学计算)中

作用:

  • 在运行时将字节码编译为机器码,减少解释器的开销。
  • 默认不会影响传统Web应用性能,但对计算密集型任务有显著提升。

启用方式: 修改php.ini

opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing

 

适用场景:

  • 数值计算
  • 图像处理或视频编解码

 2 Union Types(联合类型)

允许定义多个类型,用于函数参数,返回值或属性

<?php
 function calculate(int|float $a, int|float $b):int|float{

    return $a+$b;
 }
 echo calculate(10,10.2);//20.2

优势:

提高代码灵活性,

明确表达接受的类型

3 Named Arguments (命名参数)

函数调用时可以通过参数名指定值,避免记忆参数顺序。

 function createUser(int $age,string $sex, string $name,string $phone){

    return "姓名".$name . "年龄" .$age."性别".$sex."电话".$phone;
 }
 echo createUser(sex:"男",phone:"+86123",age:18,name:"xz");//姓名xz年龄18性别男电话+86123

特点

可读性强,

支持部分参数使用命名方式,其余使用位置参数

4 Attributes(属性/注解)

PHP原生支持注解,用于为代码元素(类,方法,属性)添加元数据

#[MyAttribute1rer]
class MyClass{
    #[MyAttribute2('private')]
   public string $name = "dd";
   public $age;
   public function test(){

   }
 }

适用场景:

框架配置(如路由定义)

数据校验规则

5 match表达式

match是一种新型分支控制结构,功能类似于switch,但是有一下关键区别:

match比较分支值,适用了严格比较(===),而switch语句使用了松散比较。

match表达式会返回一个值。

match的分支不会像switch语句一样,落空时执行下个case.

match表达式必须彻底列举所有情况。

$code = 500;
$status = match($code){
    200=>"ok",
    404=>"Not Found",
    500=>"Server Error",
    default=>"Unknown",
};
echo $status;

6 枚举

Enum类似class, 它合class,interface,trait共享同样的命名空间。enum提供了一种更清晰,更安全的方式来管理固定的值集。

enum Status{
    case Pending;
    case Approved;
    case Reject;
}
$status =  Status::Pending;
if($status === Status::Pending){
    echo "The status is pending.";

}

Backed Enum(带值枚举)

PHP支持枚举绑定到特定的值(整数或字符串),称为Backed Enum

enum UserRole: string {
    case Admin = 'admin';
    case Editor = 'editor';
    case Viewer = 'viewer';
}
// 从值获取枚举实例
$role = UserRole::from('admin');
echo $role->name; // 输出 "Admin"

// 获取枚举值
echo $role->value; // 输出 "admin"

 7  Constructor Property Promotion (构造函数属性提升)

简化类属性和赋值过程

传统写法

 

class Person{

    public string $name;
    private int $age;

    public function __construct( string $name,int $age) {
        $this->name = $name;
        $this->age = $age;
    }

 public function getInfo(){

      echo  $this->name;

 }

}
$user = new Person('zhangsan1',18);
$user->getInfo();

PHP8写法

class User {

    public  function __construct( public string $name,public string $gender){
       
    }
    public function getInfo() {
        echo  $this->name;
    }
}
$user = new User('zhangan2','nan');
$user->getInfo();

8 Nullsafe Operator (空安全操作符)

避免访问null对象属性或方法时抛出错误

传统写法

if($user !== null || $user->profile !== null ){
     
    echo 111;
}else{
    echo 222;
}

新写法

$address =  $user?->profile;

9  新字符串函数

PHP8引入了以下字符串处理函数

str_contains():检查字符串是否包含子字符串

str_starts_with()检查字符串是否以指定字符串开头

str_ends_with()检查字符串是否以指定字符串结尾

var_dump(str_contains(" hello world xmz" ,'wor'));//bool(true)
var_dump(str_starts_with("nice to meet you",'nic'));//bool(true) 
var_dump(str_ends_with("enndddds",'cs'));// bool(false)

10 错误处理改进

PHP8 提升了许多场景错误的处理方式

提升为异常

$result  = strlen(null);

 

E_WARING 和E_NOTICE 类型的错误现在会抛出ErrorException

捕获异常时可以省略变量

try{

}catch(Exception  ){

}

 

11 WeakMap类

WeakMap允许将对象作为键,并且当对象销毁时,键值会自动移除

$map = new WeakMap();
$obj = new Person('1',2);
$map[$obj] = 222;

适用场景

缓存管理

12 String接口

所有实现__toString()方法的类会自动实现Stringable接口

class Demo{

    public function __toString(){

    }
}
class Demo2{

}
var_dump(  new Demo()  instanceof  Stringable );//bool(true) 
var_dump(  new Demo2()  instanceof  Stringable );//bool(false)

13 类型系统改进

支持static作为返回类型

类型安全增强

内置函数更严格地验证类型

14 性能优化

JIT提升计算密集型场景的性能

优化引擎:改进了垃圾回收机制和字节码缓存

 

posted @ 2024-12-27 14:58  X__cicada  阅读(1204)  评论(0)    收藏  举报