– Trong lập trình hướng đối tượng, hàm __destruct() thường được khai báo bên trong một lớp, PHP sẽ tự động gọi hàm này ở cuối tập lệnh.
– Khi bạn tạo một đối tượng, hàm __destruct() sẽ tự động được gọi ở cuối tập lệnh.
<?php
class Mobile{
public $model;
function __construct($input_model){
$this->model = $input_model;
}
function __destruct(){
echo "Model: " . $this->model;
}
}
$samsung = new Mobile("Samsung Galaxy 3");
echo "------ Dưới đây là thông tin sản phẩm ------ <br>";
?>
– Dưới đây là một ví dụ khác.
<?php
class Mobile{
public $model;
public $color;
public $price;
function __construct($input_model, $input_color, $input_price){
$this->model = $input_model;
$this->color = $input_color;
$this->price = $input_price;
}
function __destruct(){
echo "Model {$this->model} <br> Màu sắc: {$this->color} <br> Giá sản phẩm: {$this->price}";
}
}
$samsung = new Mobile("Samsung Galaxy 3", "Blue", "3.500.000");
echo "------ Dưới đây là thông tin sản phẩm ------ <br>";
?>