PHP OOP에서 메소드 체이닝을 위한 안전한 추출 연산자
안전한 추출 연산자 ?->는
호출 체인에 적용될 수 있습니다.
예제를 통해 살펴보겠습니다.
다음과 같은 클래스들이 있다고 가정해 보겠습니다:
<?php
class User {
public $city = null;
}
class City {
public function getName() {
return 'city name';
}
}
?>
사용자의 도시를 다음과 같은 체인을 통해 얻고 싶다고 가정해 보겠습니다:
<?php
$user = new User();
$user->city = new City();
echo $user->city->getName();
?>
도시가 null인 경우,
이러한 체인 호출은 오류를 일으킵니다:
<?php
$user = new User();
$user->city = null;
echo $user->city->getName(); // 오류
?>
오류를 억제하기 위해 안전한 추출 연산자를 사용할 수 있습니다:
<?php
$user = new User();
$user->city = null;
echo $user->city?->getName();
?>
이제 도시도 null일 수 있다고 가정해 보겠습니다.
이 경우 안전한 추출 연산자를 두 번 사용할 수 있습니다:
<?php
$user = null;
echo $user?->city?->getName();
?>
안전한 추출 연산자를 사용하여 다음 코드를 개선하세요:
<?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();
?>