PHP 8 引入了许多新的语言特性和改进,以提升开发效率、增加代码可读性和减少错误。以下是一些 PHP 8 的新特性和代码示例:// PHP 8 之前
function example($param1, $param2, $param3) {
// ...
}
example(1, 2, 3);
// PHP 8 使用命名参数
function example($param1, $param2, $param3) {
// ...
}
example(param1: 1, param2: 2, param3: 3);
2 Nullsafe Operator(空安全操作符):// PHP 8 之前
$result = $obj->getA();
if ($result !== null) {
$result = $result->getB();
if ($result !== null) {
$result = $result->getC();
}
}
// PHP 8 使用空安全操作符
$result = $obj?->getA()?->getB()?->getC();
3 Match Expression(匹配表达式):// PHP 8 之前
switch ($value) {
case 'a':
$result = 1;
break;
case 'b':
$result = 2;
break;
default:
$result = 0;
}
// PHP 8 使用匹配表达式
$result = match($value) {
'a' => 1,
'b' => 2,
default => 0,
};
// PHP 8 之前
/**
* @param int|string $value
* @return int|string
*/
function example($value) {
// ...
}
// PHP 8 使用联合类型声明
function example(int|string $value): int|string {
// ...
}
5 Constructor Property Promotion(构造函数属性提升):// PHP 8 之前
class MyClass {
public $prop1;
public $prop2;
public function __construct($prop1, $prop2) {
$this->prop1 = $prop1;
$this->prop2 = $prop2;
}
}
// PHP 8 使用构造函数属性提升
class MyClass {
public function __construct(public $prop1, public $prop2) {
// 不再需要显式的赋值
}
}
// PHP 8 之前
class MyClass {
/**
* @var int
*/
public $value;
}
// PHP 8 使用属性
#[Attribute]
class MyAttribute {
// ...
}
#[MyAttribute]
class MyClass {
#[MyAttribute]
public $value;
}
7 Throw Expression(抛出表达式):// PHP 8 之前
function example($value) {
if ($value === null) {
throw new InvalidArgumentException('Value cannot be null');
}
// ...
}
// PHP 8 使用抛出表达式
function example($value) {
$value ?? throw new InvalidArgumentException('Value cannot be null');
// ...
}
// PHP 8 之前
$obj = new stdClass();
$map = [];
$map[$obj] = 'value';
// PHP 8 使用弱映射
$obj = new stdClass();
$map = new WeakMap();
$map[$obj] = 'value';
9 New String Functions(新的字符串函数):// PHP 8 新增字符串函数
$contains = str_contains('Hello World', 'World');
$startsWith = str_starts_with('Hello World', 'Hello');
$endsWith = str_ends_with('Hello World', 'World');
10 Saner Numeric Strings(更合理的数字字符串):// PHP 8 之前
$number = '42';
$integer = (int) $number;
// PHP 8 使用更合理的数字字符串转换
$number = '42';