メインコンテンツへ移動

เนื้อหาภาษาไทย / タイ語のコンテンツ

システムガイド 内容確認済み

OOP: Constructor and Destructor

บทความนี้อธิบายถึง Constructor และ Destructor ซึ่งเป็น Methods พิเศษใน OOP ที่ใช้ในการจัดการ Object ตั้งแต่การสร้าง (Constructor) โดยการกำหนดค่าเริ่มต้น และการท...

OOP: Constructor and Destructor

ในบทเรียนที่แล้ว เราได้เรียนรู้เกี่ยวกับ Properties และ Methods ซึ่งเป็นส่วนประกอบหลักของ Class ใน Object-Oriented Programming (OOP) ในบทนี้ เราจะมาทำความรู้จักกับ Constructor และ Destructor ซึ่งเป็น Methods พิเศษที่มีบทบาทสำคัญในการจัดการ Object ตั้งแต่การสร้างจนถึงการทำลาย

Constructor คืออะไร?

Constructor คือ Method พิเศษที่ถูกเรียกใช้งานโดยอัตโนมัติเมื่อมีการสร้าง Object ใหม่จาก Class นั้นๆ โดยมีชื่อ Method เป็น __construct() หน้าที่หลักของ Constructor คือการกำหนดค่าเริ่มต้นให้กับ Properties ของ Object หรือทำการ initialize Object ให้พร้อมใช้งาน

เหตุผลเชิงออกแบบ: Constructor ช่วยให้เรามั่นใจได้ว่าทุก Object ที่สร้างขึ้นจะมีสถานะที่ถูกต้องและพร้อมใช้งานเสมอ โดยไม่ต้องเขียนโค้ด initialize ซ้ำๆ ทุกครั้งที่สร้าง Object ใหม่ นอกจากนี้ยังช่วยลดโอกาสในการเกิดข้อผิดพลาดจากการลืมกำหนดค่าเริ่มต้นให้กับ Properties บางตัว

แนวปฏิบัติที่ดี:

  • ใช้ Constructor เพื่อกำหนดค่าเริ่มต้นที่จำเป็นสำหรับ Object
  • หลีกเลี่ยงการใส่ Logic ที่ซับซ้อนมากเกินไปใน Constructor ควรเน้นที่การ initialize Object เท่านั้น
  • ใช้ Parameter ใน Constructor เพื่อรับค่าจากภายนอกและกำหนดค่าให้กับ Properties

ตัวอย่าง Constructor ใน PHP

class User {
    public $name;
    public $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
        echo "User object created!\n";
    }

    public function greet() {
        return "Hello, my name is " . $this->name . " and my email is " . $this->email;
    }
}

$user1 = new User("John Doe", "john.doe@example.com");
echo $user1->greet(); // Output: Hello, my name is John Doe and my email is john.doe@example.com

ในตัวอย่างนี้ Constructor __construct() รับ Parameter $name และ $email จากนั้นกำหนดค่าให้กับ Properties $this->name และ $this->email เมื่อเราสร้าง Object $user1 Constructor จะถูกเรียกใช้งานโดยอัตโนมัติและกำหนดค่าเริ่มต้นให้กับ Object

Constructor Overloading (PHP ไม่รองรับโดยตรง)

ในภาษา OOP บางภาษา (เช่น Java, C++) สามารถมี Constructor หลายตัวที่มี Parameter ที่แตกต่างกันได้ (Constructor Overloading) แต่ PHP ไม่รองรับ Constructor Overloading โดยตรง เราสามารถใช้ Default Parameter หรือเทคนิคอื่นๆ เพื่อให้ได้ผลลัพธ์ที่คล้ายคลึงกัน

class Product {
    public $name;
    public $price;

    public function __construct($name, $price = 0.0) {
        $this->name = $name;
        $this->price = $price;
    }

    public function getPrice() {
        return $this->price;
    }
}

$product1 = new Product("T-Shirt", 25.0);
$product2 = new Product("Hat");

echo $product1->getPrice(); // Output: 25
echo $product2->getPrice(); // Output: 0

ในตัวอย่างนี้ Constructor __construct() รับ Parameter $price ซึ่งมี Default Value เป็น 0.0 ถ้าเราไม่ได้ส่งค่า $price เมื่อสร้าง Object Constructor จะใช้ Default Value แทน

Destructor คืออะไร?

Destructor คือ Method พิเศษที่ถูกเรียกใช้งานโดยอัตโนมัติเมื่อ Object ถูกทำลาย (destroyed) หรือเมื่อไม่มีการอ้างอิงถึง Object นั้นๆ อีกต่อไป โดยมีชื่อ Method เป็น __destruct() หน้าที่หลักของ Destructor คือการ Clean up Resource ที่ Object ใช้งาน เช่น การปิด Connection ฐานข้อมูล หรือการ Release Memory

เหตุผลเชิงออกแบบ: Destructor ช่วยให้เรามั่นใจได้ว่า Resource ที่ Object ใช้งานจะถูก Release อย่างถูกต้องเมื่อ Object ไม่จำเป็นอีกต่อไป ช่วยป้องกัน Memory Leak และปัญหาอื่นๆ ที่อาจเกิดขึ้นจากการจัดการ Resource ที่ไม่ถูกต้อง

แนวปฏิบัติที่ดี:

  • ใช้ Destructor เพื่อ Release Resource ที่ Object ใช้งาน
  • หลีกเลี่ยงการใส่ Logic ที่ซับซ้อนมากเกินไปใน Destructor ควรเน้นที่การ Clean up Resource เท่านั้น
  • ไม่ควรพึ่งพา Destructor มากเกินไปในการจัดการ Resource ควรพิจารณาใช้เทคนิคอื่นๆ เช่น RAII (Resource Acquisition Is Initialization)

ตัวอย่าง Destructor ใน PHP

class DatabaseConnection {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = mysqli_connect($host, $username, $password, $database);
        if (!$this->connection) {
            die("Connection failed: " . mysqli_connect_error());
        }
        echo "Database connection established!\n";
    }

    public function __destruct() {
        mysqli_close($this->connection);
        echo "Database connection closed!\n";
    }
}

$db = new DatabaseConnection("localhost", "username", "password", "database");
// Database connection established!
unset($db);
// Database connection closed!

ในตัวอย่างนี้ Constructor __construct() สร้าง Connection ฐานข้อมูล และ Destructor __destruct() ปิด Connection ฐานข้อมูล เมื่อเรา unset($db) Object $db จะถูกทำลาย และ Destructor จะถูกเรียกใช้งานโดยอัตโนมัติ

ข้อควรระวัง: การเรียกใช้ Destructor ไม่ได้เกิดขึ้นทันทีหลังจากที่ Object ไม่มีการอ้างอิงถึงอีกต่อไป PHP Garbage Collector จะเป็นผู้จัดการในการทำลาย Object และเรียกใช้ Destructor ดังนั้นเราไม่สามารถคาดเดาเวลาที่ Destructor จะถูกเรียกใช้งานได้อย่างแม่นยำ

ลำดับการทำงานของ Constructor และ Destructor

เมื่อ Class มีทั้ง Constructor และ Destructor ลำดับการทำงานจะเป็นดังนี้:

  1. Constructor จะถูกเรียกใช้งานเมื่อมีการสร้าง Object ใหม่
  2. โค้ดอื่นๆ ที่เกี่ยวข้องกับ Object จะถูกประมวลผล
  3. Destructor จะถูกเรียกใช้งานเมื่อ Object ถูกทำลาย

Inheritance และ Constructor/Destructor: เมื่อ Class มีการ Inheritance Constructor และ Destructor ของ Parent Class จะถูกเรียกใช้งานก่อน Constructor และ Destructor ของ Child Class ตามลำดับ

class Animal {
    public function __construct() {
        echo "Animal constructor called.\n";
    }

    public function __destruct() {
        echo "Animal destructor called.\n";
    }
}

class Dog extends Animal {
    public function __construct() {
        parent::__construct(); // Call parent constructor
        echo "Dog constructor called.\n";
    }

    public function __destruct() {
        echo "Dog destructor called.\n";
        parent::__destruct(); // Call parent destructor
    }
}

$dog = new Dog();
// Output:
// Animal constructor called.
// Dog constructor called.

unset($dog);
// Output:
// Dog destructor called.
// Animal destructor called.

ในตัวอย่างนี้ เมื่อเราสร้าง Object $dog Constructor ของ Animal จะถูกเรียกใช้งานก่อน Constructor ของ Dog และเมื่อเรา unset($dog) Destructor ของ Dog จะถูกเรียกใช้งานก่อน Destructor ของ Animal

สรุป

Constructor และ Destructor เป็น Methods พิเศษที่มีบทบาทสำคัญในการจัดการ Object ใน PHP Constructor ใช้สำหรับกำหนดค่าเริ่มต้นให้กับ Object และ Destructor ใช้สำหรับ Clean up Resource ที่ Object ใช้งาน การเข้าใจและใช้งาน Constructor และ Destructor อย่างถูกต้องจะช่วยให้เราเขียน Code OOP ที่มีประสิทธิภาพและปลอดภัยมากยิ่งขึ้น ในบทต่อไป เราจะเรียนรู้เกี่ยวกับ Inheritance ซึ่งเป็นอีกหนึ่งแนวคิดสำคัญใน OOP

Office.in.th Custom Service

この構成をもとにシステムを開発・カスタマイズしたいですか?

Office.in.th は、エンタープライズ Web アプリケーション、API 連携、官民の業務管理システムの設計・開発を承り、長期的なサポートも提供します。

ソフトウェア開発サービスを見る