PHP 8 interview question · Most asked
What does the nullsafe operator `?->` do?
Summary
?-> short-circuits a method or property chain and returns null as soon as the left-hand side is null, instead of throwing an error.
Longer Answer
It replaces nested null checks such as $user !== null && $user->getAddress() !== null ? ... : null. When any element in the chain evaluates to null, the rest of the chain is skipped, including argument evaluation.
It is read-only: you cannot use it on the left of an assignment ($a?->b = 1 is a compile error), and it cannot be used with references.
Code Example
<?php
$country = $session?->user?->getAddress()?->country ?? 'Unknown';
Key Points
- Returns
nullinstead of erroring on a null receiver - Short-circuits the entire remaining chain
- Not allowed in write context
- Pairs well with
??to supply a default
Explanation
Common mistakes
- Overusing
?->to hide data integrity problems that should throw - Using it in assignments
More most-asked PHP 8 questions
- How should passwords be stored in PHP?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- What are union types in PHP 8 and how do you use them?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are enums in PHP 8.1? Explain pure vs backed enums.
- What are the most important features introduced in PHP 8.0?