Null Coalescing Operator ?? and ??=
The null coalescing operator is the perfect tool for defaults. It checks for null (and unset variables) without triggering notices, and it chains beautifully.
// Before: verbose isset checks
$username = isset($_GET['user']) ? $_GET['user'] : 'anonymous';
$config = isset($options['timeout']) ? $options['timeout'] : 30;
// After: clean and obvious
$username = $_GET['user'] ?? 'anonymous';
$config = $options['timeout'] ?? 30;
// Chaining — try multiple sources, fall back gracefully
$color = $user->preference('color') ?? $team->default('color') ?? '#777BB4';
// Null coalescing assignment (PHP 7.4)
$this->cache ??= []; // Initialize only if null
$options['retries'] ??= 3; // Set default without overwriting
// Perfect for lazy initialization
public function getLogger(): LoggerInterface {
return $this->logger ??= new NullLogger();
}
Unlike the ternary operator, ?? specifically checks for null — not falsy values. 0, '', and false pass through, which is almost always what you want. This distinction alone prevents countless bugs.
Significance: Pragmatism
PHP's shared-nothing architecture means every request starts fresh, and default values are everywhere. The null coalescing operator turns a three-line
isset check into three characters, making the most common PHP pattern — "use this value or fall back to that one" — effortless to write and read.