บทนำ
ใน OOP Constructor คือเมธอดที่ถูกเรียกโดยอัตโนมัติเมื่อสร้างออบเจ็กต์ใหม่ ใช้สำหรับ Initialize (เริ่มต้นค่า) ออบเจ็กต์ ใน PHP ใช้เมธอดชื่อ __construct
Syntax
__construct ([ mixed $args = "" [, $... ]] ) : void
ตัวอย่าง Constructor พื้นฐาน
<?php
class myclass {
function __construct() {
echo "object initialized";
}
}
$obj = new myclass();
?>
ผลลัพธ์
object initialized
Constructor กับ Arguments
ใช้สำหรับ Initialize Properties ด้วยค่าที่ส่งมา:
<?php
class rectangle {
var $height;
var $width;
function __construct($arg1, $arg2) {
$this->height = $arg1;
$this->width = $arg2;
}
function show() {
echo "Height=$this->height Width=$this->width";
}
}
$obj = new rectangle(10, 20);
$obj->show();
?>
ผลลัพธ์
Height=10 Width=20
Constructor ใน Inheritance
ถ้า Parent มี Constructor ให้เรียกด้วย parent::__construct() ใน Child Constructor ถ้า Child ไม่มี Constructor จะสืบทอดจาก Parent มาโดยอัตโนมัติ
<?php
class a {
function __construct() {
echo "this is a constructor of base class\n";
}
}
class b extends a {
function __construct() {
parent::__construct();
echo "this a constructor class b\n";
}
}
class c extends a { // ไม่มี constructor - สืบทอดจาก a
}
$a = new a();
$b = new b();
$c = new c();
?>
ผลลัพธ์
this is a constructor of base class this is a constructor of base class this a constructor class b this is a constructor of base class
Destructor
Destructor เรียกโดยอัตโนมัติเมื่อ Garbage Collector พบว่าออบเจ็กต์ไม่มี Reference อีกต่อไป (หรือเมื่อ Script จบการทำงาน) ใช้เมธอดชื่อ __destruct ไม่รับ Arguments และไม่ Return ค่า
<?php
class myclass {
function __construct() {
echo "object is initialized\n";
}
function __destruct() {
echo "object is destroyed\n";
}
}
$obj = new myclass();
?>
ผลลัพธ์
object is initialized object is destroyed
ข้อสังเกตสำคัญ
- PHP 5+ ใช้
__construct()(PHP 4 ใช้ชื่อคลาสเป็น Constructor - Deprecated) - Destructor เรียกเมื่อ Object ถูก Destroy ไม่ใช่ทันทีที่ออก Scope
- ใน Destructor ไม่ควรทำ Heavy Operations (อาจช้าตอน Shutdown)
- Exception ใน Destructor จะถูก Ignore (ยกเว้น PHP 7.4+ ที่ log ไว้)