Web Development

PHP: Method Chaining

02 มิถุนายน 20231 นาที
0
PHP: Method Chaining
Table of Contents

PHP Method Chaining

คือ การเรียกใช้ Method ต่อเนื่องกัน โดยไม่ต้องเก็บค่าที่ return มาไว้ในตัวแปร แล้วเรียกใช้ต่อ แต่จะเรียกใช้ต่อเลย โดยการเรียกใช้ Method ต่อเนื่องกัน จะต้อง return $this กลับมา แล้วเรียกใช้ต่อไป

ตัวอย่าง

  • Class ที่ไม่ใช้ Method Chaining
PHP Logo
class Car { private $brand; private $color; public function setBrand($brand) { $this->brand = $brand; } public function setColor($color) { $this->color = $color; } public function drive() { echo "Driving the $this->color $this->brand car."; } } $car = new Car(); $car->setBrand('Toyota'); $car->setColor('blue'); $car->drive();
  • Class ที่ใช้ Method Chaining
PHP Logo
class Car { private $brand; private $color; public function setBrand($brand) { $this->brand = $brand; return $this; // Return $this to enable method chaining } public function setColor($color) { $this->color = $color; return $this; // Return $this to enable method chaining } public function drive() { echo "Driving the $this->color $this->brand car."; } } $car = new Car(); $car->setBrand('Toyota')->setColor('blue')->drive();

จะเห็นว่า Class ที่ใช้ Method Chaining จะเรียกใช้งานได้สะดวกและ Code ดูสวยกว่ามากๆ

Tags:PHP

คลิกเพื่อแสดงความคิดเห็น