PHP 7.4中空合并赋值运算符??=是什么?与??运算符有何区别?
??) vs Null Coalescing Assignment (??=) Operators: What's the Difference? Hey there! I’ve seen a lot of developers scratch their heads when they first encounter ??= after using ?? for years, so let’s break these two down with clear examples and plain language.
First: The Original ?? (Null Coalescing Operator)
Introduced in PHP 7.0, this operator is all about safe value retrieval. It checks if the left-hand variable/expression exists and isn’t null — if it does, it returns that value; if not, it falls back to the right-hand value.
It’s a way cleaner replacement for the old isset() + ternary combo. Here’s how it works:
// Pre-PHP 7.0 clunky way $username = isset($_GET['user']) ? $_GET['user'] : 'Anonymous'; // With ?? operator (so much cleaner!) $username = $_GET['user'] ?? 'Anonymous';
You can even chain it for multiple fallbacks:
$displayName = $user['full_name'] ?? $user['username'] ?? 'Guest';
The key thing here: ?? returns a value — you have to assign it to a variable, echo it, or use it directly in an expression.
Next: The Newer ??= (Null Coalescing Assignment Operator)
PHP 7.4 added this shorthand to make default-value assignments even simpler. It’s essentially a shortcut for $var = $var ?? $fallback; — meaning it only assigns the fallback value to the left-hand variable if that variable is null or doesn’t exist. If the variable already has a non-null value, it stays exactly as it is.
Check out the example:
// Longhand with ?? (repeating the variable name) $settings['layout'] = $settings['layout'] ?? 'grid'; // Shorthand with ??= (no repetition!) $settings['layout'] ??= 'grid';
This is perfect for setting defaults in arrays or class properties without overwriting existing valid data:
// Set config defaults only if keys don't exist $config['timeout'] ??= 30; $config['max_retries'] ??= 5;
Core Differences at a Glance
- Purpose:
??retrieves a value (with fallback) and requires you to handle the result (assign, echo, etc.)??=directly assigns a fallback value only when necessary (never overwrites non-null values)
- Use case:
??works in any expression:echo $user['email'] ?? 'no-email@example.com';??=is strictly for assignment:$user['email'] ??= 'no-email@example.com';(can’t use it directly in an echo)
- Brevity:
??=eliminates redundant variable name repetition, making your code cleaner and less error-prone.
内容的提问来源于stack exchange,提问作者Mike Doe

