PHP 8 interview question · Most asked
Compare `??`, `?:`, and `?->`.
Summary
?? returns the left operand unless it is null/undefined, ?: returns the left operand unless it is falsy, and ?-> safely calls a method or property on a possibly-null object.
Longer Answer
$a ?? $b doesn't emit a warning for undefined variables or keys, making it ideal for $_GET['x'] ?? 'default'. $a ?: $b treats 0, '', '0', [] and false as missing, which is often a bug for numeric input. ?-> chains through nulls. ??= (PHP 7.4) assigns only when null.
Key Points
??checks null/undefined only?:checks falsiness (beware0and'0')?->short-circuits on null in chains??=assigns if null
Comparison / Tradeoffs
| Operator | Falls back when | Example |
|---|---|---|
?? |
null or undefined | $_GET['page'] ?? 1 |
?: |
falsy | $name ?: 'Anonymous' |
?-> |
receiver is null | $user?->profile |
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.