PHP 8 Modern Syntax & Features

Match expressions, named arguments, constructor property promotion, readonly properties, enums, fibers and the JIT — the syntax that modernized PHP.

IntermediateUpdated 2026-10-2943K views

match and Nullsafe Operator

// match:严格比较(===),必须穷尽,返回值
$code = 404;
$message = match ($code) {
    200, 201 => 'success',
    404      => 'not found',
    500      => 'server error',
    default  => 'unknown',
};

// nullsafe:链上任意一环为 null 则整体为 null
$city = $user?->getAddress()?->city ?? 'unknown';

// 联合类型与返回类型
function formatId(int|string $id): int|string {
    return is_int($id) ? $id : strtoupper($id);
}

Constructor Promotion, Readonly and Enums

<?php
// 构造器属性提升:一行声明 + 赋值
class Point {
    public function __construct(
        public readonly float $x,   // 只读:构造后不可变
        public readonly float $y,
    ) {}
}

$p = new Point(1.5, 2.5);
echo $p->x; // 1.5

// 枚举(PHP 8.1+):带值的强类型枚举
enum Status: string {
    case Active   = 'active';
    case Disabled = 'disabled';
}

$s = Status::from('active');   // 值 -> 枚举
$s->value;                      // 'active'
$s === Status::Active;          // true
readonly plus enums make PHP DTOs nearly immutable-by-construction; pair them with promoted properties to remove boilerplate getters.

Fibers and the JIT

  • Fibers (8.1) are lightweight, user-land coroutines — the foundation of async frameworks like Swoole, RoadRunner and ReactPHP.
  • The JIT (8.0) compiles hot paths to machine code, speeding CPU-bound code; IO-bound web apps benefit less than expected.
  • Attributes (8.0) replace doc-block annotations for declarative config in Symfony and Laravel.

Friends & Partners