Modern PHP Tips for Cleaner Code
Small modern PHP features — match, the null-safe operator, named arguments, enums and readonly properties — that make code easier to read.
PHP 8 added features that remove a lot of boilerplate. If you still write PHP the old way, these are worth adopting.
match instead of switch
$label = match ($status) {
'draft' => 'Draft',
'published' => 'Live',
default => 'Unknown',
};
match returns a value, uses strict comparison and has no fall-through bugs.
The null-safe operator
// Before
$city = $user && $user->address ? $user->address->city : null;
// After
$city = $user?->address?->city;
Named arguments
htmlspecialchars($text, double_encode: false);
Skip optional parameters you do not need and make calls self-explanatory.
Constructor property promotion
class InvoiceMailer
{
public function __construct(
private Mailer $mailer,
private string $from = '[email protected]',
) {}
}
Enums
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
}
$status = Status::from($row['status']);
No more typos in magic strings — your editor and PHP itself check the values.
Readonly properties
final class Money
{
public function __construct(
public readonly int $amount,
public readonly string $currency,
) {}
}
Arrow functions
$names = array_map(fn ($user) => $user->name, $users);
Arrow functions capture outer variables automatically and keep short callbacks on one line.
Need help with your website?
I build fast, SEO-ready websites and web applications.