PHP 8: Modern PHP Development · Modern PHP Syntax & Types
match, Nullsafe and Modern Operators
Use match expressions, the nullsafe operator and null coalescing to write concise, safe code.
match (8.0) is an expression that compares with strict identity (===), returns a value, needs no break, and throws UnhandledMatchError if nothing matches — much safer than switch. The nullsafe operator ?-> short-circuits a chain to null when an intermediate value is null. Combine with ?? (null coalescing) and ??= for defaults.
<?php
$label = match ($status) {
'draft', 'pending' => 'Not published',
'published' => 'Live',
default => throw new InvalidArgumentException("Unknown status {$status}"),
};
// match(true) for ranges
$grade = match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
default => 'C',
};
$country = $user?->getAddress()?->country ?? 'Unknown';
$options['timeout'] ??= 30;
Common pitfalls
- Expecting
matchto coerce types likeswitch—match('1')won't match1. - Using
?->in write context ($a?->b = 1) — not allowed. - Overusing nullsafe chains to hide design problems where null should be impossible.
Key points
matchis strict, exhaustive and returns a valuethrowis an expression in PHP 8?->and??handle optional values concisely
Further reading: PHP manual: match
Practice questions
Give three differences between match and switch.
Answer
match uses strict comparison (===), is an expression that returns a value, and has no fall-through (no break). It also throws UnhandledMatchError when no arm matches, while switch silently does nothing.
What does $a?->b()?->c return if b() returns null?
Answer
null — the nullsafe operator short-circuits the rest of the chain, so c isn't accessed and no error is raised.
Open in the app to mark lessons complete, take notes and track your progress.