Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

The nullsafe operator ?->

Reference for the PHP 8 nullsafe operator ?->: chain method calls and property reads that stop safely when a value is null, with short-circuit rules.

The nullsafe operator ?-> (added in PHP 8.0) reads a property or calls a method only when the object on its left is not null. If the left side is null, the whole rest of the chain is skipped and the result is null. It replaces long ladders of if ($a !== null && $a->b !== null) checks.

It only guards against null. It does not protect you from a missing property, a missing method, or a value that is not an object at all.

PHP
$city = $user?->getAddress()?->city;

Try it

PHP Chaining through null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Short-circuiting skips the whole chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$object?->property
$object?->method(arguments)
$object?->first()?->second()
Part Description
Left side Any expression. If it is null, evaluation of the rest of the chain stops.
Right side A property name or a method call, exactly as with ->.

Return value: the property value or method result when the left side is an object, otherwise null.

Errors: if the left side is neither null nor an object, PHP behaves as with -> (a warning when reading a property of a non-object, an Error when calling a method on one). Calling an undefined method on a real object still throws Error.

Usage notes

  • Short-circuit. When the left side is null, the rest of the chain is not evaluated at all, including argument expressions of later calls and later ?-> links. The second example shows loud("argument B") never runs.
  • Only null is skipped. false, 0 and "" are not objects, so false?->method() throws an Error instead of giving null.
  • Combine with ??. $a?->b ?? "default" gives a fallback when the chain ends in null. See ??.
  • Reading only for properties. You cannot assign through it ($a?->b = 1 is a compile-time error), and it cannot be used with & references or inside unset().
  • Does not replace isset(). On a real object, reading an undefined property still produces a warning. Use isset() for that.
  • Do not hide design problems. If a value should always exist, a null check that silently passes may be worse than a clear exception.
  • Static members. ?-> is not for ::. Use it with instances only.
  • Added in PHP 8.0. Earlier versions have no equivalent syntax.