PHP OOP - Penghancur
PHP - Fungsi __destruct
Destruktor dipanggil ketika objek dirusak atau skrip dihentikan atau keluar.
Jika Anda membuat __destruct()
fungsi, PHP akan secara otomatis memanggil fungsi ini di akhir skrip.
Perhatikan bahwa fungsi destruct dimulai dengan dua garis bawah (__)!
Contoh di bawah ini memiliki fungsi __construct() yang secara otomatis dipanggil saat Anda membuat objek dari kelas, dan fungsi __destruct() yang secara otomatis dipanggil di akhir skrip:
Contoh
<?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");
?>
Contoh lain:
Contoh
<?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");
?>
Tip: Karena konstruktor dan destruktor membantu mengurangi jumlah kode, mereka sangat berguna!