0
0
PHPprogramming~5 mins

Null safe operator in PHP

Choose your learning style9 modes available
Introduction

The null safe operator helps you safely access properties or methods of an object that might be null, avoiding errors.

When you want to get a value from an object that might not exist.
When you want to call a method on an object that could be null.
When you want to avoid writing extra checks for null before accessing properties.
When you want cleaner and shorter code instead of many if statements.
Syntax
PHP
$result = $object?->property;
$result = $object?->method();

The ?-> operator checks if the object is not null before accessing.

If the object is null, the whole expression returns null instead of causing an error.

Examples
This tries to get name from $user. Since $user is null, $name becomes null and no error happens.
PHP
$user = null;
$name = $user?->name;
echo $name;
Here, $user is an object with a name. The null safe operator returns 'Anna'.
PHP
$user = new stdClass();
$user->name = 'Anna';
$name = $user?->name;
echo $name;
Calling a method on a null object safely returns null instead of error.
PHP
$user = null;
$length = $user?->getNameLength();
echo $length;
Calls method on a real object and prints the length.
PHP
class User {
    public function getNameLength() {
        return strlen('Anna');
    }
}
$user = new User();
$length = $user?->getNameLength();
echo $length;
Sample Program

This program shows how the null safe operator lets you access properties and methods safely when the object might be null.

PHP
<?php
class User {
    public ?string $name;
    public function getNameLength(): ?int {
        return $this->name ? strlen($this->name) : null;
    }
}

$user1 = new User();
$user1->name = 'John';
$user2 = null;

// Using null safe operator
echo $user1?->name . "\n";          // Prints 'John'
echo $user2?->name . "\n";          // Prints nothing (null)
echo $user1?->getNameLength() . "\n"; // Prints 4
echo $user2?->getNameLength() . "\n"; // Prints nothing (null)
OutputSuccess
Important Notes

The null safe operator was introduced in PHP 8.0.

It helps avoid many if checks for null before accessing objects.

If the object is null, the whole expression returns null, so be careful when printing or using the result.

Summary

The null safe operator ?-> lets you access properties or methods safely on objects that might be null.

It returns null instead of causing an error if the object is null.

This makes your code shorter and easier to read when dealing with optional objects.