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 null instead 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

← All PHP 8 questions