Metode __destruct

Fungsi __destruct adalah metode magis dalam PHP yang secara otomatis dipanggil ketika objek dihapus dari memori. Ini terjadi baik ketika skrip selesai berjalan, atau ketika objek secara eksplisit dihancurkan. Metode ini berguna untuk membebaskan resource (misalnya menutup deskriptor file atau koneksi database).

Sintaks

phpclass MyClass {
  public function __destruct() {
    // kode destruktor
  }
}

Contoh

Contoh sederhana kelas dengan destruktor yang menampilkan pesan saat objek dihancurkan:

php<?php
class Test {
  public function __destruct() {
    echo 'Object destroyed';
  }
}

$obj = new Test();
unset($obj); // Akan memanggil destruktor
?>

Hasil eksekusi kode:

php'Object destroyed'

Contoh

Contoh dengan membebaskan resource (menutup file):

php<?php
class FileHandler {
  private $file;

  public function __construct($filename) {
    $this->file = fopen($filename, 'r');
  }

  public function __destruct() {
    if ($this->file) {
      fclose($this->file);
      echo 'File closed';
    }
  }
}

$handler = new FileHandler('example.txt');
// Bekerja dengan file...
unset($handler); // Akan menutup file secara otomatis
?>

Hasil eksekusi kode:

php'File closed'

Lihat juga