Web Development

PHP: Inheritance

07 มกราคม 20231 นาที
0
PHP: Inheritance
Table of Contents

PHP Inheritance

คือ การสืบทอดคุณสมบัติ และ พฤติกรรม จาก Class หลัก ไปยัง Class ย่อย

Extend

การสืบทอดคุณสมบัติ และ พฤติกรรม จาก Class หลัก ไปยัง Class ย่อย ใช้คำสั่ง extends

PHP Logo
class Car { public $brand; public $model; public $color; public $year; public $price; public function __construct($brand, $model, $color, $year, $price) { $this->brand = $brand; $this->model = $model; $this->color = $color; $this->year = $year; $this->price = $price; } public function getCarInfo() { return "Brand: " . $this->brand . ", Model: " . $this->model . ", Color: " . $this->color . ", Year: " . $this->year . ", Price: " . $this->price; } } class Toyota extends Car { public $country; public $engine; public function __construct($brand, $model, $color, $year, $price, $country, $engine) { parent::__construct($brand, $model, $color, $year, $price); $this->country = $country; $this->engine = $engine; } public function getCarInfo() { return parent::getCarInfo() . ", Country: " . $this->country . ", Engine: " . $this->engine; } } $toyota = new Toyota("Toyota", "Vios", "White", 2019, 500000, "Japan", "1.5L"); echo $toyota->getCarInfo();

Access Modifier

  • public สามารถเข้าถึงได้ทุกที่

  • protected สามารถเข้าถึงได้ภายใน Class และ Class ที่สืบทอดมา

  • private สามารถเข้าถึงได้ภายใน Class เท่านั้น

  • public everything is accessible

  • protected is self and child class

  • private is self class only

Tags:PHP

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