PHP 8 Features
Leverage PHP 8+ enums, attributes, constructor promotion, match, fibers, and JIT improvements.
Constructor Promotion and Union Types
Constructor property promotion declares and assigns properties in constructor signatures, reducing boilerplate DTO classes.
Union types int|string and mixed replacement patterns document acceptable inputs. Intersection types require multiple interfaces simultaneously.
Named arguments improve readability when calling functions with many optional parameters—order independent.
- Combine promotion with readonly for value objects
- Static analysis tools leverage types for bugs
- Avoid overusing mixed—narrow types at boundaries
class Point {
public function __construct(
public float $x,
public float $y,
) {}
}
function connect(string $host, int $port = 443) {}
connect(host: 'db.internal', port: 3306);Enums and Match
Backed enums enum Status: string { case Active = 'active'; } replace magic strings with type-safe sets. Methods can be added to enums for behavior.
match expressions return values exhaustively with default arms catching unhandled cases—stricter than switch.
Nullsafe operator ?-> chains property access without nested isset checks.
- Serialize enums carefully in APIs—use value property
- Use tryFrom for parsing untrusted strings
- Exhaustive match catches new enum cases at compile time in static analysis
enum OrderStatus: string {
case Pending = 'pending';
case Shipped = 'shipped';
}
$label = match ($status) {
OrderStatus::Pending => 'Processing',
OrderStatus::Shipped => 'On the way',
};Attributes and Fibers
Attributes #[Route('/api')] replace docblock annotations for metadata consumed by frameworks via reflection.
Fibers enable cooperative concurrency in low-level libraries; most web developers interact via async frameworks built atop them.
JIT in OPcache benefits CPU-heavy workloads; measure before enabling in typical CRUD apps where I/O dominates.
- Prefer attributes over comments for machine-readable config
- Upgrade hosting to PHP 8.3+ for latest security fixes
- Read migration guides when jumping major PHP versions
#[Attribute]
class CacheTtl {
public function __construct(public int $seconds) {}
}
#[CacheTtl(300)]
function expensiveStats(): array { /* ... */ }