Definition:
The null-safe operator is represented by ?->. When you use this operator in a program, it checks whether the object used in the program is null or has some value/text. If it finds that the object is null, it stops the operation; if the object is not null and has some text/value, it continues the operation.
Syntax:
$object?->property; $object?->method();
Example:
<?php
class Profile {
public $age = 25;
}
class User {
public ?Profile $profile = null;
}
$user1 = new User();
$user1->profile = new Profile();
$user2 = new User(); // profile is null
// Accessing age safely
echo $user1->profile?->age; // 25
echo "<br>";
echo $user2->profile?->age; // null, no error
?>
Output:
25
Note:
The second line gives null, but there is no error because of the null-safe operator.
