circle-chevron-rightDestructor

destructor จะแตกต่างกันในแต่ละภาษา แต่ถ้าโดยรวมก็เป็น method ที่ให้ class ทำอะไรบางอย่างก่อนที่ class นั้นจะถูกทำลายลง

PHP

Destructor ใน PHP จะมีชื่อ method ว่า __destruct()

Example code

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

C

เป็น function พิเศษ ในภาษาC ที่จะใช้ในการคืนพื้นที่ ที่ obj ใช้

Example code

Java

ในJava จะมี garbage collector ที่รันที่ JVM ที่จะคอยเคลียพื้นที่ ที่ไม่ได้ใช้อยู่แล้ว แต่การที่เราจะควบคุม garbage collector นั้นเป็นเรื่องยาก Java จึงมีอีกทางหนึ่งที่ เราสามารถทำได้ คือ ใช้method finalize() ที่ทำหน้าที่คล้าย destructor

Examplecode

Python

ในPython destructor จะถูกเรียกในตอนที่ obj นั้นถูกทำลาย มีชื่อว่า __delarrow-up-right__() method แต่มันก็ไม่ได้จำเป็นขนาดนั้น เพราะ python เอง ก็มี garbage collector ที่คอยทำให้อัตโนมัติ

Examplecode

อ้างอิง

ภาษา PHP

https://www.w3schools.com/php/php_oop_destructor.asparrow-up-right

ภาษา C https://bito.ai/resources/c-destructor-c-explained/#:~:text=A%20C%20destructor%20is%20a%20special,with%20it%20for%20other%20uses.arrow-up-right

ภาษา Java

https://www.javatpoint.com/java-destructorarrow-up-right

ภาษา Python

https://www.geeksforgeeks.org/destructors-in-python/arrow-up-right

Last updated 1 minute ago

Last updated