PHP OOP - 析构函数
PHP - __destruct() 函数
当对象被销毁,或脚本停止或退出时,析构函数会被调用。
如果您创建了一个 __destruct()
函数,PHP 将在脚本结束时自动调用此函数。
请注意,析构函数以两个下划线(__)开头!
下面的示例包含一个 __construct() 函数(在创建类的对象时自动调用),以及一个 __destruct() 函数(在脚本结束时自动调用)。
示例
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "水果是 {$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 "水果是 {$this->name} 颜色是 {$this->color}。";
}
}
$apple = new Fruit("Apple", "red");
?>
自己动手试一试 »
提示: 构造函数和析构函数非常有用,可以帮助减少代码量!