From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like:

echo $data->getMyObject()?->getName() ?? '';

By using ?-> instead of -> the chain of operators is terminated and the result will be null.

The operators that "look inside an object" are considered part of the chain.

  • Array access ([])
  • Property access (->)
  • Nullsafe property access (?->)
  • Static property access (::)
  • Method call (->)
  • Nullsafe method call (?->)
  • Static method call (::)

e.g. for the code:

$string = $data?->getObject()->getName() . " after";

if $data is null, that code would be equivalent to:

$string = null . " after";

As the string concatenation operator is not part of the 'chain' and so isn't short-circuited.

Answer from Danack on Stack Overflow
🌐
PHP.Watch
php.watch › versions › 8.0 › null-safe-operator
Null-safe operator - PHP 8.0 • PHP.Watch
The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null, without causing any errors.
🌐
PHP
wiki.php.net › rfc › nullsafe_operator
PHP: rfc:nullsafe_operator
June 2, 2020 - When the left hand side of the operator evaluates to null the execution of the entire chain will stop and evalute to null.
Discussions

Is there a "nullsafe operator" in PHP? - Stack Overflow
From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like: More on stackoverflow.com
🌐 stackoverflow.com
Null Safe Operator for PHP 7.x or Earlier - Stack Overflow
PHP 8 has introduced an amazing code fallback tool, Null Safe Operator, eg: $country = $session?->user?->getAddress()?->country; It prevents you create a lot of comparisons of all whole o... More on stackoverflow.com
🌐 stackoverflow.com
The null safe operator in PHP 8
160k members in the Wordpress community. **Welcome to r/WordPress** A Reddit devoted to all things WordPress More on reddit.com
🌐 r/Wordpress
PHP 8: the nullsafe operator
This alone will get me to switch to 8 More on reddit.com
🌐 r/laravel
15
82
May 4, 2020
🌐
Stitcher
stitcher.io › blog › php-8-nullsafe-operator
PHP 8: the null safe operator | Stitcher.io
November 17, 2020 - The null safe operator allows you to safely call methods and properties on nullables on PHP 8.
🌐
Medium
medium.com › @prevailexcellent › mastering-null-safety-in-php-8-a-comprehensive-guide-to-using-the-null-safe-operator-47835ba1140b
Mastering Null Safety in PHP 8: A Comprehensive Guide to Using the Null Safe Operator | by Chimeremze Prevail Ejimadu | Medium
June 14, 2023 - However, PHP 8 introduces the null safe operator (also known as the null safe navigation operator or the null conditional operator), denoted by ?->, which simplifies null handling and enhances code readability.
Top answer
1 of 4
83

From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like:

echo $data->getMyObject()?->getName() ?? '';

By using ?-> instead of -> the chain of operators is terminated and the result will be null.

The operators that "look inside an object" are considered part of the chain.

  • Array access ([])
  • Property access (->)
  • Nullsafe property access (?->)
  • Static property access (::)
  • Method call (->)
  • Nullsafe method call (?->)
  • Static method call (::)

e.g. for the code:

$string = $data?->getObject()->getName() . " after";

if $data is null, that code would be equivalent to:

$string = null . " after";

As the string concatenation operator is not part of the 'chain' and so isn't short-circuited.

2 of 4
14

Nullsafe operator allows you to chain the calls avoiding checking whether every part of chain is not null (methods or properties of null variables).

PHP 8.0

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

Before PHP 8.0

$city = null;
if($user !== null) {
    $address = $user->getAddress();
    if($address !== null) {
        $city = $address->city;
    }
}

With null coalescing operator (it doesn't work with methods):

$city = null;
if($user !== null) {
    $city = $user->getAddress()->city ?? null;
}

Nullsafe operator suppresses errors:

Warning: Attempt to read property "city" on null in Fatal error:

Uncaught Error: Call to a member function getAddress() on null

However it doesn't work with array keys:

$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null

$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"
🌐
PHP
php.net › manual › en › language.oop5.basic.php
PHP: The Basics - Manual
The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return.
🌐
Exakat
exakat.io › home › null safe operator in practice
Null safe operator in practice - Exakat
December 20, 2023 - Last elephpant cubs to snatch>>> ... Null-safe operator has been added to PHP 8.1: it is a new object operator that prevents a Fatal error, and its following execution stop, when calling a method or a property on the null value.
Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › simplifying-if-else-php-ternary-null-safe-operators-md-enamul-haque-vgqqc
Simplifying if-else in PHP with Ternary and Null Safe Operators
April 1, 2024 - The Null Safe operator ?-> in PHP is utilized for accessing properties or methods of an object that might be null without causing a runtime error. If the left-hand side of the operator is null, the entire expression short-circuits and evaluates ...
🌐
DEV Community
dev.to › frknasir › php-null-safe-and-null-coalescing-operators-jg2
PHP null-safe and null-coalescing operators - DEV Community
July 6, 2021 - $eating; The null-safe is a PHP8 feature that, instead of throwing an exception, short-circuits to null when a chained property or method access is null and the rest of the chain is skipped.
Top answer
1 of 4
1

To emulate null safe operator, you can take inspiration from the option type. The idea is simple - you wrap the value in an object, as you suggested, and have a magic method handling. Now, the magic method will either return $this - e.g. the same Option instance, if this is already a null, or call the method and wrap the result in an Option, to allow further chaining.

The challenge you face with PHP will be where to terminate, e.g. where to return the original value, and not the wrapper. If you can afford an explicit method call at the end of the chain, it becomes straightforward.

It would look something like (not tested, written for illustrative purposes)

class Option {
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function __call($methodName, $args) {
        if (is_null($this->value)) {
            return $this;
        }
        return new Option($this->value->$methodName($args));
    }

    public function __get($propertyName) {
        if (is_null($this->value)) {
            return $this;
        }
        return new Option($this->value->$propertyName);
    }

    public function get() {
        return $this->value;
    }
}

So you will do:

$country = new Option($session)->user->getAddress()->country->get();
2 of 4
0

We can create a black holed class to instead of throw an exception return Null if we call an undefined method of a generic class which will acts as our fallback.

    <?php
    // _7 - for brevity write and 7 is closer to question mark ;)
    class _7  {
        public function __call($method, $args) return null;
    }


$myDate = (\DateTime::createFromFormat('d/m/Y','05/04/1989') ?: new _7)->format('Y-m-d') ?? 'Bad date';
//'1989-04-05' - because expected date format is provided to Datetime 

$myDate = (\DateTime::createFromFormat('d/m/Y','1989') ?: new _7)->format('Y-m-d') ?? 'Bad date';
//'Bad date' - Very cool! No exceptions here, successfull fallback;

Important! This approach only works with PHP >= 7.0, i will collect info to work with 5.x soon as possible.

🌐
DEV Community
dev.to › nvahalik › comparing-phps-null-safe-operator-with-another-null-safe-operator-can-bite-you-4k7p
Comparing PHP's Null-safe operator with another null-safe operator can bite you - DEV Community
January 20, 2025 - If the current user isn't a trainer, the first part of the right-hand expression ($user->trainer_record) will resolve to null. The left hand expression will be the ID of the user's current trainer.
🌐
Henry Petry
henrypetry.com › php8-null-safe-operator
PHP 8: Null Safe Operator
September 13, 2023 - PHP 8's Null Safe Operator is a significant step forward in making PHP code safer and more concise when dealing with potentially null values. By using this operator, you can streamline your code, reduce errors, and improve the overall robustness ...
🌐
Phpinternals
phpinternals.news › 65
PHP Internals News podcast :: Null safe operator
August 6, 2020 - So you could do something like null safe operator bar equals foo, effectively assigning the string foo something that might or might not be null. I only learnt this recently. You can also foreach over an array into the property of an object, which I've never seen before in my 20 odd years writing PHP.
🌐
dailycomputerscience
dailycomputerscience.com › post › exploring-the-php-8-nullsafe-operator
Exploring the PHP 8 Nullsafe Operator
December 12, 2025 - The nullsafe operator works similarly to the existing object operator (->), but with a built-in check for null. When PHP encounters the ?-> operator, it first checks if the object on the left-hand side is null.
🌐
DEV Community
dev.to › sureshramani › exploring-the-null-safe-operator-in-php-238k
Exploring the Null Safe Operator in PHP - DEV Community
December 30, 2023 - In traditional PHP code, dealing with null values often requires extensive checks and conditional statements, leading to verbose and error-prone code. Developers had to constantly validate whether a variable was null before accessing its properties or methods. This process was not only tedious but also increased the likelihood of introducing bugs. Enter the Null Safe Operator PHP, a game-changer that simplifies null handling and makes code more concise and readable.
🌐
Hoanguyenit
hoanguyenit.com › php8-null-safe-operator.html
PHP 8.0: Null-safe operator
November 25, 2025 - Php Tip 💡 : Null-safe operator 🎉 · Trong PHP 8, chúng ta có thể sử dụng cách viết nullsafe (?->).
🌐
TutorialsPoint
tutorialspoint.com › nullsafe-operator-in-php-8
Nullsafe Operator in PHP 8
The nullsafe syntax is like the method/property access operator(→). We use "?→" for null-safe operator. ... <?php class Emp{ public function getAddress() {} } $emp = new Emp(); $dept = $emp?->getAddress()?->dept?->iso_code; print_r($dept); ?>
🌐
Drupal
drupal.org › project › user_display_name › issues › 3308444
Php 8 null safe operator [#3308444] | Drupal.org
February 4, 2025 - Problem/Motivation The null safe operator does not work in lower versions of php. Understandably this module requires php 8 but for our usage we needed to still use php 7.4. Steps to reproduce Using an environment set up using php 7.4 visit /admin/reports/status.