Does PHP Have Safe Navigation Operator?

PHP 8 introduced the nullsafe operator (?->), which is simply another name for the safe navigation operator. It evaluates an expression from left-to-right; when/if the left-hand side of the operator evaluates to null, it stops the execution of the entire chain and short-circuit evaluates the expression to null. This helps avoid having the need to add sequential explicit null-safe checks.

You can use the nullsafe operator to call object methods or access object properties within an execution chain where an object in the chain can potentially be null. It has the following syntax:

$obj->val?->prop
$obj->val?->method()

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.