The null safe operator (?->
) in PHP is a feature introduced in PHP 8.0. It allows you to call methods or access properties on an object only if the object is not null
. If the object is null
, the operation short-circuits and returns null
instead of throwing an error.
$result = $object?->method();
This is equivalent to:
if ($object !== null) {
$result = $object->method();
} else {
$result = null;
}
Key Points:
- The null safe operator only works for method calls and property access.
- It short-circuits when encountering
null
, returningnull
instead of proceeding further. - Useful for avoiding
null
reference errors in nested object structures.
Benefits:
- Reduces boilerplate code.
- Makes the code cleaner and more readable when dealing with nullable objects.
If you’re familiar with other languages, this is similar to the optional chaining operator (?.
) in JavaScript or Kotlin.