PHP OOP - ตัวทำลาย
PHP - ฟังก์ชัน __destruct
Destructor ถูกเรียกเมื่อวัตถุถูกทำลายหรือสคริปต์หยุดหรือออก
หากคุณสร้าง__destruct()
ฟังก์ชัน PHP จะเรียกใช้ฟังก์ชันนี้โดยอัตโนมัติที่ส่วนท้ายของสคริปต์
ขอให้สังเกตว่าฟังก์ชั่นการทำลายเริ่มต้นด้วยขีดล่างสองตัว (__)!
ตัวอย่างด้านล่างมีฟังก์ชัน __struct() ที่ถูกเรียกโดยอัตโนมัติเมื่อคุณสร้างวัตถุจากคลาส และฟังก์ชัน __destruct() ที่ถูกเรียกโดยอัตโนมัติเมื่อสิ้นสุดสคริปต์:
ตัวอย่าง
<?php
class Fruit {
public
$name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
ตัวอย่างอื่น:
ตัวอย่าง
<?php
class Fruit {
public
$name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name}
and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
เคล็ดลับ:เนื่องจากตัวสร้างและตัวทำลายล้างช่วยลดจำนวนโค้ดลงได้ จึงมีประโยชน์มาก!