# PHP null-conditional operator ## Explanation Many languages nowadays have a null-conditional operator that allows checking if an object is `null` before performing operations on it. It's an addition to null-coalescing and ternary operators, but one that works for methods, not values. If a given object is not `null`, the method call is executed. If it is `null`, nothing gets executed and the result is `null` In essence, ```cs bool? foo = object?.method(); ``` is equal to ```cs bool? foo; if (object != null) { foo = object.method(); } else { foo = null; } ``` ## Proposed syntaxes ```php $object~>method(); ``` The same amount of characters to type, and the tilde looks like an uncertain kind of a dash. ```php $object?->method(); ``` Consistent with other languages, where the operator usually is `object?.method()`. ```php $object-?>method(); ``` Only needs one jump from top to bottom row when typing out, instead of one from bottom to top and from top to bottom. Could clash with the closing tag. Some more exotic syntaxes: ```php $object?>method(); // Clashes with the closing tag $object-?method(); // No arrow $object??method(); // Could clash with null-coalescing operator $object-->method(); $object_>method(); // this one is kinda cool actually, no need to let go of shift ``` ## Usage example Consider the following structure: ```php class Application { public static function getUser(): ?User { return (new UserRepository())->find($_SESSION['userid']); } } class User { private $role; public function getRole(): ?Role { return $this->role; } } class Role { /** @var string $name */ public $name; /** @var bool $is_admin */ public $is_admin; } ``` Without null-conditional operator: ```php if ( $this->getUser() && $this->getUser()->getRole() && $this->getUser()->getRole()->is_admin ){ $this->gratAccess(); } ``` or ```php $user = $this->getUser(); if ($user) { $role = $user->getRole(); if ($role) { if ($role->is_admin) { $this->gratAccess(); } } } ``` And with null-conditional operator ```php if ($this->getUser()~>getRole~>is_admin) { $this->grantAccess(); } ```