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.
$city = $user?->getAddress()?->city;
Try it
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.
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
$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 showsloud("argument B")never runs. - Only
nullis skipped.false,0and""are not objects, sofalse?->method()throws anErrorinstead of givingnull. - Combine with
??.$a?->b ?? "default"gives a fallback when the chain ends innull. See??. - Reading only for properties. You cannot assign through it (
$a?->b = 1is a compile-time error), and it cannot be used with&references or insideunset(). - Does not replace
isset(). On a real object, reading an undefined property still produces a warning. Useisset()for that. - Do not hide design problems. If a value should always exist, a
nullcheck 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.