积木成楼
首页 / php

php8.1新特性与部分使用实践

2022-01-20 · php · 约 11 分钟

php8.x 的实用特性与使用

php8 中的实用特性

命名参数

public function response(array $data = [],int $code = 200,string $msg = "") : array
{
	return ['data'=> $data, 'code'=> $code,'msg' => $msg];
}

// php7
$this->response([],200,"其他的提示信息");//非必须参数只能按顺序写

// php8以后
$this->response(msg: "其他的提示信息")//指定参数传入与响应

Nullsafe 运算符

$user = null;

// php7
if($user){
	$order = $user->lastOrder();
    if($order){
        $discountAmount = $order->getDiscountAmount();	
    }
}
//对于参数对象可能为 null 并且会执行方法的情况 ?? 就没法去处理了

// php8 以后 
$discountAmount = $user?->lastOrder()?->getDiscountAmount();

枚举类型 & match 表达式

enum ResponseCode: int
{
    case SUCCESS = 200;
    case SYS_ERROR = 500;

    public static function getMessageByCode(int $code): string
    {
        $responseCode = self::tryFrom($code);
        if (!$responseCode) {
            return '未定义错误码';
        }
        return self::getMessage($responseCode);
    }

    private static function getMessage(self $value): string
    {
        return match ($value) {
            self::SUCCESS => "成功",
            self::SYS_ERROR => "系统错误",
        };
     }
}
// 响应值构造使用
public function success(array|object $data = [], string $msg = "", int|object $code = ResponseCode::SUCCESS): JsonResponse
{
    $res = new stdClass();
    $res->data = $data ?: (object)[];
    $res->code = is_object($code) ? $code->value : $code;
    $res->msg = $msg ?: ResponseCode::getMessageByCode($res->code);
    return response()->json($res);
}

php8opcachejit(Just In Time)

← 返回文章列表