แนะนำตัว
การสืบทอดเป็นหลักการสำคัญของวิธีการเขียนโปรแกรมเชิงวัตถุ โดยใช้หลักการนี้ ความสัมพันธ์ระหว่างสองคลาสสามารถกำหนดได้ PHP รองรับการสืบทอดในรูปแบบวัตถุ
PHP ใช้ ขยาย คีย์เวิร์ดเพื่อสร้างความสัมพันธ์ระหว่างสองคลาส
ไวยากรณ์
class B extends A
โดยที่ A คือคลาสพื้นฐาน (เรียกอีกอย่างว่า parent ที่เรียก) และ B ถูกเรียกว่าคลาสย่อยหรือคลาสย่อย คลาสลูกสืบทอดเมธอดสาธารณะและได้รับการป้องกันของคลาสพาเรนต์ คลาสย่อยอาจกำหนดใหม่หรือแทนที่วิธีการใด ๆ ที่สืบทอดมา หากไม่เป็นเช่นนั้น เมธอดที่สืบทอดมาจะคงฟังก์ชันการทำงานตามที่กำหนดไว้ในคลาสพาเรนต์ เมื่อใช้กับอ็อบเจ็กต์ของคลาสย่อย
คำจำกัดความของคลาสพาเรนต์ต้องมาก่อนนิยามคลาสย่อย ในกรณีนี้ คำจำกัดความของคลาส A ควรปรากฏก่อนคำจำกัดความของคลาส B ในสคริปต์
ตัวอย่าง
<?php
class A{
//properties, constants and methods of class A
}
class B extends A{
//public and protected methods inherited
}
?> หากเปิดใช้งานการโหลดอัตโนมัติ คำจำกัดความของคลาสพาเรนต์จะได้รับจากการโหลดสคริปต์คลาส
ตัวอย่างการสืบทอด
รหัสต่อไปนี้แสดงว่าคลาสย่อยสืบทอดสมาชิกสาธารณะและสมาชิกที่ได้รับการป้องกันของคลาสหลัก
ตัวอย่าง
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class\n" ;
}
private function privatemethod(){
echo "This is private method of parent class\n" ;
}
}
class childclass extends parentclass{
public function childmethod(){
$this->protectedmethod();
//$this->privatemethod(); //this will produce error
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?> ผลลัพธ์
ซึ่งจะให้ผลลัพธ์ตามมา −
This is public method of parent class This is protected method of parent class PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context 'childclass'
ตัวอย่างการแทนที่วิธีการ
หากเมธอดที่สืบทอดมาจากคลาสพาเรนต์ถูกกำหนดใหม่ในคลาสย่อย นิยามใหม่จะแทนที่ฟังก์ชันก่อนหน้า ในตัวอย่างต่อไปนี้ publicmethod ถูกกำหนดอีกครั้งในคลาสย่อย
ตัวอย่าง
<?php
class parentclass{
public function publicmethod(){
echo "This is public method of parent class\n" ;
}
protected function protectedmethod(){
echo "This is protected method of parent class\n" ;
}
private function privatemethod(){
echo "This is private method of parent class\n" ;
}
}
class childclass extends parentclass{
public function publicmethod(){
echo "public method of parent class is overridden in child class\n" ;
}
}
$obj=new childclass();
$obj->publicmethod();
?> ผลลัพธ์
ซึ่งจะให้ผลลัพธ์ตามมา −
public method of parent class is overridden in child class
มรดกตกทอด
PHP ไม่รองรับการสืบทอดหลายรายการ ดังนั้นคลาสไม่สามารถขยายสองคลาสขึ้นไปได้ อย่างไรก็ตาม รองรับการสืบทอดมรดกแบบทายาทดังนี้:
ตัวอย่าง
<?php
class A{
function test(){
echo "method in A class";
}
}
class B extends A{
//
}
class C extends B{
//
}
$obj=new C();
$obj->test();
?> ผลลัพธ์
ซึ่งจะแสดงผลดังต่อไปนี้
method in A class