⊗ppOpAdNOC 21 of 107 menu

Safe Extraction Operator in Chains in OOP in PHP

The safe extraction operator ?-> can be used in call chains. Let's look at an example. Suppose we have the following classes:

<?php class User { public $city = null; } class City { public function getName() { return 'city name'; } } ?>

Suppose we want to get the user's city through the chain:

<?php $user = new User(); $user->city = new City(); echo $user->city->getName(); ?>

In case the city is equal to null, calling such a chain will cause an error:

<?php $user = new User(); $user->city = null; echo $user->city->getName(); // error ?>

To suppress the error, we can use the safe extraction operator:

<?php $user = new User(); $user->city = null; echo $user->city?->getName(); ?>

Suppose now the city can also be null. In this case, we can use the operator safe extraction twice:

<?php $user = null; echo $user?->city?->getName(); ?>

Improve the following code using the safe extraction operator:

<?php class Employee { public $name; public $position; public function __construct($name, $position) { $this->name = $name; $this->position = $position; } } class Position { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } $position = new Position('developer'); $employee = new Employee('john', $position); echo $employee->position->getName(); ?>
byenru