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

ข้อดีของการใช้ __construct() แทนชื่อคลาสเป็น Constructor ใน PHP


ใช่ มีข้อดีหลายประการในการใช้ฟังก์ชันแมจิก __construct() แทนการใช้ชื่อคลาสเป็น Constructor ข้อดีเหล่านี้มีดังนี้:

  • ฟังก์ชันแมจิก __construct ถูกนำเข้ามาใน PHP 5 (ไม่ใช่ 5.4 ตามที่เขียนผิดในต้นฉบับ) ข้อดีหนึ่งคือ หากคุณเปลี่ยนชื่อคลาส คุณไม่ต้องไปแก้ไข Constructor ซึ่งสนับสนุนหลักการ DRY (Don't Repeat Yourself)
  • หากมีคลาสลูก (Child Class) คุณสามารถเรียก parent::__construct() เพื่อเรียก Constructor ของคลาสแม่ได้อย่างง่ายดาย

ตัวอย่าง

<?php 
class myclass{ 
    public function __construct(){ 
        echo 'The class "', __CLASS__, '" was initiated!'."\n"; 
    } 
} 
class childclass extends myclass{ 
    public function __construct() { 
        parent::__construct(); 
        print "In SubClass constructor "; 
    } 
} 
$myobj = new childclass(); 
?>

ผลลัพธ์

The class "myclass" was initiated! 
In SubClass constructor

หมายเหตุ

"__CLASS__" เป็นแมจิกคอนสแตนต์ (Magic Constant) ซึ่งในกรณีนี้จะคืนค่าชื่อของคลาสที่ถูกเรียก

Constructor แบบเก่า (ใช้ชื่อคลาส) ถูก Deprecated ใน PHP 7.0 และจะถูกลบในอนาคต ควรใช้ __construct() เสมอในโค้ดใหม่