Säker hämtningsoperator i kedjor i OOP i PHP
Säker hämtningsoperator ?->
kan användas i anropskedjor.
Låt oss titta på ett exempel.
Anta att vi har följande klasser:
<?php
class User {
public $city = null;
}
class City {
public function getName() {
return 'stadens namn';
}
}
?>
Anta att vi vill få användarens stad genom kedjan:
<?php
$user = new User();
$user->city = new City();
echo $user->city->getName();
?>
Om staden är null,
kommer ett sådant kedjeanrop att leda till ett fel:
<?php
$user = new User();
$user->city = null;
echo $user->city->getName(); // fel
?>
För att undertrycka felet kan vi använda säker hämtningsoperator:
<?php
$user = new User();
$user->city = null;
echo $user->city?->getName();
?>
Anta nu att staden också kan vara null.
I det här fallet kan vi använda operatorn
för säker hämtning två gånger:
<?php
$user = null;
echo $user?->city?->getName();
?>
Förbättra följande kod med säker hämtningsoperator:
<?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('utvecklare');
$employee = new Employee('john', $position);
echo $employee->position->getName();
?>