The Analogy: The Workshop Retooled with Modern Power Tools
Consider a joiner's workshop that has been in the family for decades. The old master could build anything with a hand saw, a chisel, and long experience -- but every cut was slow, and a moment's lapse of concentration meant a crooked joint or a nicked thumb. Then the workshop is retooled: a mitre saw that cuts a perfect angle every time, a jig that holds the piece square so it cannot slip, a guard that makes the dangerous cut safe. The work is the same furniture, but the new tools make the right result easier and the wrong result harder. PHP 8's modern features are that retooling. The language can still do everything it did before, but the new constructs make correct code shorter and mistakes structurally harder to make.
The best new tools do not just save effort; they remove whole categories of error. The mitre saw's angle stop means you cannot accidentally cut 43 degrees when you meant 45 -- the tool refuses the wrong result. PHP 8's match expression is like this: unlike the old switch, it compares strictly, has no fall-through, and must be exhaustive or it throws, so the classic switch bugs -- a forgotten break, a loose == surprise -- simply cannot occur. The tool's shape prevents the mistake rather than merely warning about it.
Some tools make intent visible to the next person who picks up the work. A labelled jig shows at a glance how the piece is meant to sit. Named arguments do this for function calls -- makeBox(width: 5, height: 3) says what each number means at the call site -- and readonly properties announce "this value never changes after construction", so a reader knows a field is safe to rely on. The code documents itself through the tools it uses.
The failure mode is the workshop that buys the new tools but keeps working the old way, or misuses them. A joiner who bolts on the safety guard and then removes it because it is "in the way" has spent money to be no safer. In PHP this is the developer who writes PHP 8 but still reaches for switch with its fall-through traps, hand-checks nulls that the nullsafe operator would handle, or mutates objects that should be readonly value objects. Worse is misusing a tool against its grain -- an over-broad match(true) that hides logic a clear if would show. The tools are leverage only when used as intended; adopting the syntax without adopting the discipline it encodes leaves you with newer code that is no more correct than the old.
Syntax or Core Structure
The match expression is the flagship PHP 8 feature: it returns a value, compares strictly, and never falls through. Paired with named arguments, calls become both safer and self-documenting.
<?php
declare(strict_types=1);
function grade(int $score): string {
return match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
$score >= 70 => 'C',
default => 'F',
};
}
echo grade(95), grade(83), grade(72), grade(50), "\n";
function makeBox(int $w, int $h, string $color = 'white'): string {
return "$w x $h $color";
}
echo makeBox(h: 3, w: 5), "\n";
echo makeBox(w: 2, h: 2, color: 'red'), "\n";
Output:
ABCF
5 x 3 white
2 x 2 red
The match (true) returns the first branch whose condition is true, giving A, B, C, and F for the four scores -- as an expression, its result is returned directly. The named-argument calls pass h and w in any order while staying readable, and the second call names every argument including the optional color. Because match is strict and exhaustive, and named arguments bind by name not position, both features remove a class of mistakes the older switch and positional calls allowed.
Technical Depth: Nullsafe, Readonly, and First-Class Callables
A tour of the headline features
PHP 8 added many features across its point releases. These are the ones you will reach for daily.
| Feature | Since | What it gives |
|---|---|---|
match | 8.0 | Strict, exhaustive, expression-valued branching |
| Named arguments | 8.0 | Order-independent, self-documenting calls |
| Constructor promotion | 8.0 | Declare and assign properties in the signature |
Nullsafe ?-> | 8.0 | Short-circuit a chain on null |
readonly properties | 8.1 | Immutable-after-construction fields |
First-class callable ... | 8.1 | Turn a function/method into a Closure |
The nullsafe operator
Chained property access used to require a ladder of null checks. The nullsafe operator ?-> short-circuits the whole chain to null the moment any link is null, pairing naturally with ?? for a default.
<?php
declare(strict_types=1);
final class Address { public function __construct(public ?string $city = null) {} }
final class User { public function __construct(public ?Address $address = null) {} }
function cityOf(?User $u): string {
return $u?->address?->city ?? 'unknown';
}
$full = new User(new Address('London'));
$noCity = new User(new Address());
$noAddr = new User();
echo cityOf($full), "\n";
echo cityOf($noCity), "\n";
echo cityOf($noAddr), "\n";
echo cityOf(null), "\n";
Output:
London
unknown
unknown
unknown
The chain $u?->address?->city yields London for the fully-populated user. For every other case -- a user with an address but no city, a user with no address, and a null user -- the chain short-circuits to null at the first missing link, and ?? 'unknown' supplies the default. Without ?->, each of these would need an explicit null guard or would raise an error on property access of null.
Readonly properties and first-class callables
A readonly property can be set once, in the constructor, and never again -- perfect for value objects. The first-class callable syntax fn(...) turns any function or method into a Closure without a wrapping lambda.
<?php
declare(strict_types=1);
final class Point {
public function __construct(
public readonly int $x,
public readonly int $y,
) {}
}
$p = new Point(3, 4);
echo "point: {$p->x},{$p->y}\n";
try {
$p->x = 10;
} catch (\Error $e) {
echo 'error: ', $e->getMessage(), "\n";
}
$fn = strlen(...);
echo 'via closure: ', $fn('hello'), "\n";
$lengths = array_map(strlen(...), ['a', 'bb', 'ccc']);
echo 'lengths: ', implode(',', $lengths), "\n";
Output:
point: 3,4
error: Cannot modify readonly property Point::$x
via closure: 5
lengths: 1,2,3
The Point reads back its coordinates, but attempting to reassign $p->x throws an Error -- readonly enforces immutability at the engine level, not by convention. The first-class callable strlen(...) produces a Closure you can call directly or pass to array_map, giving lengths 1,2,3 for the three strings, all without writing fn($s) => strlen($s). These features together make immutable, functional-flavoured code concise and safe.
String helper functions
PHP 8.0 finally added str_contains, str_starts_with, and str_ends_with, replacing the error-prone strpos(...) !== false idiom whose classic trap is that a match at position 0 returns a falsy 0.
<?php
declare(strict_types=1);
$path = 'report-2026.pdf';
echo 'contains 2026: ', str_contains($path, '2026') ? 'yes' : 'no', "\n";
echo 'starts report: ', str_starts_with($path, 'report') ? 'yes' : 'no', "\n";
echo 'ends .pdf: ', str_ends_with($path, '.pdf') ? 'yes' : 'no', "\n";
echo 'ends .csv: ', str_ends_with($path, '.csv') ? 'yes' : 'no', "\n";
$oldWrong = strpos($path, 'report') ? 'truthy' : 'falsy-0-BUG';
echo 'old idiom at pos 0: ', $oldWrong, "\n";
Output:
contains 2026: yes
starts report: yes
ends .pdf: yes
ends .csv: no
old idiom at pos 0: falsy-0-BUG
The three helpers return clean booleans: the filename contains 2026, starts with report, ends with .pdf but not .csv. The final line shows the trap they replace: strpos($path, 'report') returns 0 because the match is at the start, and 0 is falsy, so the old idiom wrongly reports falsy-0-BUG unless you carefully wrote !== false. The dedicated functions express intent directly and eliminate the footgun entirely, and because they read as plain English they make the calling code easier to review at a glance.
Real World Example: An Immutable HttpStatus Value Object
A value object that classifies HTTP status codes shows several PHP 8 features working together: readonly properties for immutability, a named constructor, and a match for the classification logic. The result is a small, safe, self-documenting type.
<?php
declare(strict_types=1);
final class HttpStatus {
public function __construct(
public readonly int $code,
public readonly string $reason,
) {}
public static function from(int $code): self {
$reason = match (true) {
$code >= 200 && $code < 300 => 'Success',
$code >= 300 && $code < 400 => 'Redirect',
$code >= 400 && $code < 500 => 'Client Error',
$code >= 500 => 'Server Error',
default => 'Informational',
};
return new self($code, $reason);
}
public function isError(): bool {
return $this->code >= 400;
}
}
foreach ([200, 301, 404, 503, 100] as $code) {
$s = HttpStatus::from($code);
$flag = $s->isError() ? ' [error]' : '';
echo "{$s->code} {$s->reason}$flag\n";
}
Output:
200 Success
301 Redirect
404 Client Error [error]
503 Server Error [error]
100 Informational
The from named constructor uses match (true) to classify a code into a reason phrase, then builds an immutable HttpStatus whose code and reason are readonly. The loop shows each code mapped correctly, with isError flagging the 4xx and 5xx codes. Once built, a status cannot be tampered with, and the match makes the classification exhaustive and clear. This is idiomatic modern PHP: an immutable value object with a named constructor and expression-based logic.
The design flaw is that match (true) with range conditions silently accepts nonsensical codes -- HttpStatus::from(9999) returns 9999 Server Error, and from(-5) returns -5 Informational via the default branch -- because the constructor validates nothing. The class models "a reason for any integer" rather than "a valid HTTP status", so it cannot refuse an impossible code; the readonly immutability then faithfully preserves the nonsense. A stricter value object would validate in the constructor (or a factory) and throw for codes outside the real 100-599 range, making an invalid HttpStatus unrepresentable rather than merely mislabelled. This is the deeper lesson about value objects: immutability guarantees a value will not change, but it says nothing about whether the value was valid to begin with, and the two guarantees must be provided separately. A modern type that is immutable but unvalidated gives false confidence, because a reader assumes a readonly value object holds a legitimate value -- an assumption this class does not actually enforce. The idiom that closes the gap is "always valid by construction": make every path that creates the object run through validation, mark the constructor private and expose only validating named constructors like from, and throw the moment an invalid value is supplied. Then the type's mere existence is proof of validity, and every downstream consumer can rely on it without re-checking -- which is the whole point of a value object, and exactly what an immutable-but-unvalidated class fails to deliver.
Common Mistakes
- Still using
switchwherematchfits.switchhas loose comparison and fall-through traps. Prefermatchfor strict, exhaustive, expression-valued branching.
- Overusing
match(true). Cramming complex conditional logic intomatch(true)can obscure it. Use a plainifwhen the logic reads more clearly that way.
- Ignoring the nullsafe operator. Hand-rolling null-check ladders is verbose and error-prone. Use
?->with??for a default.
- Mutating what should be readonly. Leaving value-object fields writable invites accidental change. Mark them
readonlyso immutability is enforced.
- Treating readonly as validation.
readonlystops later change but does not check the initial value. Validate in the constructor separately.
- Positional calls where names clarify. A call like
makeBox(5, 3, true)hides what the arguments mean. Use named arguments for clarity.
- Writing lambdas where
fn(...)suffices.fn($x) => strlen($x)is noise whenstrlen(...)works. Use the first-class callable syntax.
- Assuming a feature exists in your PHP version.
readonlyis 8.1, enums 8.1,match8.0. Check the minimum version you target before relying on one.
- Adopting syntax without the discipline. Using PHP 8 constructs while keeping old habits gains little. Let the tools enforce the correctness they are designed for.
Best Practices
- Prefer
matchoverswitchfor its strict comparison, absence of fall-through, and expression value.
- Reach for
match(true)for clean range or condition mapping, but drop toifwhen that reads more clearly.
- Use the nullsafe operator with
??to collapse null-check ladders into one readable expression.
- Make value-object fields
readonly, and validate their values in the constructor, treating immutability and validity as separate guarantees.
- Use named arguments to make call sites self-documenting, especially for booleans and optional parameters.
- Prefer the first-class callable syntax
fn(...)over a wrapping lambda when passing a function or method.
- Adopt constructor property promotion to declare and assign value-object fields in one place.
- Confirm the PHP version you target supports a feature before relying on it, since several arrived across the 8.x releases.
Practice Exercises
- Rewrite a
switch-based grade classifier as amatch (true)expression that returns the grade, and confirm it handles boundary scores correctly.
- Build a two-level object graph and a function using
?->and??to read a deep property safely, demonstrating it returning a default when a link is null.
- Define a
readonlyPointvalue object, show that reassigning a field throws anError, and passstrlen(...)toarray_mapusing the first-class callable syntax.
- Create an immutable
HttpStatusvalue object with a named constructor and amatch, then add constructor validation that throws for codes outside 100-599, making an invalid status unrepresentable.