ตัวดำเนินการเข้าถึงแบบปลอดภัยในสายโซ่ของ OOP ใน PHP
ตัวดำเนินการเข้าถึงแบบปลอดภัย ?->
สามารถนำมาใช้ในสายโซ่ของการเรียกได้
มาดูตัวอย่างกัน
สมมติว่าเรามีคลาสต่อไปนี้:
<?php
class User {
public $city = null;
}
class City {
public function getName() {
return 'ชื่อเมือง';
}
}
?>
สมมติว่าเราต้องการได้เมืองของผู้ใช้ ผ่านสายโซ่:
<?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();
?>