Null safe operator for class in PHP

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:

  1. The null safe operator only works for method calls and property access.
  2. It short-circuits when encountering null, returning null instead of proceeding further.
  3. 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.