The nullsafe operator is a new feature introduced in PHP 8 that allows developers to perform a series of operations on a variable, property, or method without worrying about potential null values.
In previous versions of PHP, if you attempted to call a method or access a property on a variable that was null, you would receive a fatal error. However, with the nullsafe operator, you can chain method calls and property accesses without having to check for null values at every step.
The syntax for the nullsafe operator is the question mark followed by the arrow operator (->?) or double colon (::?) depending on the type of access. For example:
$object->getProperty()?->doSomething();
In this example, if $object
is null, the entire expression will return null, and the doSomething()
method will not be called. If $object
is not null, the getProperty()
method will be called, and if it returns a non-null value, the doSomething()
method will be called on the result.
Similarly, if you need to call a static method on a potentially null class, you can use the nullsafe operator with the double colon (::?) syntax. For example:
MyClass::getInstance()?::doSomething();
In this example, if MyClass::getInstance()
returns null, the entire expression will return null, and the doSomething()
method will not be called. If MyClass::getInstance()
returns a non-null value, the doSomething()
method will be called on the result.
Overall, the nullsafe operator is a handy feature that can help simplify code and make it more readable by reducing the number of null checks and conditional statements that need to be written.