ข้ามไปยังเนื้อหาหลัก
ProgrammerThailand

PHP Object Oriented Programming (OOP)

Constructor ใน PHP

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();
?>

 

ติดปัญหาตอนทำตาม? ถามในชุมชน

ความคิดเห็น (0)

ยังไม่มีความคิดเห็น — เริ่มคุยเป็นคนแรก ถามสิ่งที่สงสัย หรือแชร์ประสบการณ์ของคุณ

แชร์