PHP 8.1(2021 年发布)

1. 语法改进

class User {
  public function __construct(
	  public string $name,
	  public int $age
  ) {}
}
function createProduct(string $name, float $price) {}
createProduct(price: 9.99, name: "Book");
$array = ["a" => 1, ...["b" => 2]]; // ["a" => 1, "b" => 2]
class Data {
  public function __construct(
	  readonly public string $value
  ) {}
}

2. 类型系统增强

function formatInput(string|int $input): string {}
function getCoordinates(): [float, float] {
  return [40.71, -74.01];
}
enum Status: string {
  case Active = 'active';
  case Inactive = 'inactive';
}
function throwError(): never {
  throw new Exception("Invalid input");
}

3. 性能优化

4. 新增内置函数

if (str_contains($text, "hello")) { ... }

5. 并发与异步

$fiber = new Fiber(function () {
  echo Fiber::suspend(); // 暂停并返回值
  echo "Resumed";
});
$fiber->start(); // 启动
$fiber->resume("Hello"); // 恢复执行

6. 其他改进

throw new Exception("Error", 0, $previousException);