Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธีเรียก Parent Constructor ใน Child Class ใน PHP


มี 2 กรณีในการเรียก Parent Constructor จาก Child Class:

กรณีที่ 1

หาก Child Class กำหนด Constructor ของตัวเอง จะไม่เรียก Parent Constructor อัตโนมัติ ต้องเรียก parent::__construct() ภายใน Child Constructor เอง

ตัวอย่าง

<?php 
class grandpa{ 
    public function __construct(){ 
        echo "I am in Tutorials Point"."\n"; 
    } 
} 
class papa extends grandpa{ 
    public function __construct(){ 
        parent::__construct(); 
        echo "I am not in Tutorials Point"; 
    } 
} 
$obj = new papa(); 
?>
Output: I am in Tutorials Point I am not in Tutorials Point

คำอธิบาย

ใช้ parent::__construct() เพื่อเรียก Constructor ของ Parent Class

กรณีที่ 2

หาก Child Class ไม่ได้กำหนด Constructor จะสืบทอดมาจาก Parent Class เหมือนเมธอดทั่วไป (ถ้าไม่ได้ประกาศเป็น private)

ตัวอย่าง

<?php 
class grandpa{ 
    public function __construct(){ 
        echo "I am in Tutorials point"; 
    } 
} 
class papa extends grandpa{ 
} 
$obj = new papa(); 
?>

ผลลัพธ์

I am in Tutorials point

คำอธิบาย

Parent Constructor ถูกเรียกโดยอัตโนมัติ เพราะ Child Class ไม่มี Constructor ของตัวเอง