wave
มานพ กองอุ่น 29 ต.ค. 2019 14:48:17 3,591

Constructor เป็น method เริ่มต้น เมื่อมีการสร้าง Object จาก Class จะเริ่มทำงานทันที โดยมีโครงสร้างดังนี้

__construct ([ mixed $args = "" [, $... ]] ) : void

ตัวอย่างการเรียกใช้งาน

<?php
class Mother {
    function __construct() {
        print "ฉันเป็นแม่\n";
    }
}

class Son extends Mother {
    function __construct() {
        parent::__construct();
        print "ฉันเป็นลูก\n";
    }
}

class Other extends Mother {
    // สืบทอด constructor มาจาก Mother
}

// ฉันเป็นแม่
$obj = new Mother();

// ฉันเป็นแม่
// ฉันเป็นลูก
$obj = new Son();

// ฉันเป็นแม่
$obj = new Other();
?>

 


ความคิดเห็น

หากบทเรียนรู้มีความผิดพลาดประการใด หรือมีข้อเสนอแนะกรุณาแจ้ง contact@programmerthailand.com

เขียนบทเรียนรู้ของคุณ

รายละเอียด
  • ดู 3,591
  • รักเลย 0
  • หมวดหมู่ PHP Object Oriented Programming (OOP)
  • เขียนเมื่อ
  • แก้ไขเมื่อ
  • Tags php oop constructor
ข้อมูลผู้เขียน
มานพ กองอุ่น

มานพ กองอุ่น

เป็นสมาชิกเมื่อ: 18 ธ.ค. 2009