Tips & tricks
Small idioms with a big payoff.
match expression
A switch that returns a value and compares strictly.
$label = match (true) {
$status >= 500 => 'server error',
$status >= 400 => 'client error',
$status >= 200 => 'ok',
default => 'unknown',
}; // strict comparison, no fall-through, returns a valuePromotion, nullsafe and named arguments
Less boilerplate, safer chains, self-documenting calls.
final class User
{
public function __construct( // constructor property promotion (8.0)
public readonly int $id,
public readonly string $email,
) {}
}
$country = $order?->customer?->address?->country; // nullsafe operator (8.0)
$user = new User(email: 'a@b.com', id: 7); // named arguments (8.0)Backed enums with methods
Replace class constants and magic strings.
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
public function label(): string
{
return ucfirst($this->value);
}
}
Status::from('draft')->label(); // "Draft"Saved in this browser only. Part of Clean code foundations (0/5).