PHP-də OOP-də Zəncirvari Çağırışlarda Təhlükəsiz Çıxarış Operatoru

Təhlükəsiz çıxarış operatoru ?-> zəncirvari çağırışlarda tətbiq edilə bilər. Nümunəyə baxaq. Tutaq ki, bizim aşağıdakı siniflərimiz var:

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

Tutaq ki, istifadəçinin şəhərini zəncir vasitəsilə almaq istəyirik:

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

Əgər şəhər null-a bərabərdirsə, belə bir zəncirin çağırılması xətaya səbəb olacaq:

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

Xətanı aradan qaldırmaq üçün biz təhlükəsiz çıxarış operatorundan istifadə edə bilərik:

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

İndi tutaq ki, şəhər də null ola bilər. Bu halda biz təhlükəsiz çıxarış operatorundan iki dəfə istifadə edə bilərik:

php<?php
  $user = null;
  
  echo $user?->city?->getName();
?>
Задание 1

Aşağıdakı kodu təhlükəsiz çıxarış operatoru vasitəsilə yaxşılaşdırın:

php<?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();
?>