PHP OOP - 析构函数

PHP - __destruct 函数

当对象被销毁或脚本停止或退出时,会调用析构函数。

如果您创建一个 __destruct() 函数,PHP 将在脚本结束时自动调用此函数。

请注意,析构函数以两个下划线(__)开头!

下面的例子有一个 __construct() 函数,当您从类中创建一个对象时会自动调用它,以及一个 __destruct() 函数,它会在脚本结束时自动调用:

实例

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

亲自试一试

另一个例子:

实例

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

亲自试一试

提示:由于构造函数和析构函数有助于减少代码量,因此它们非常有用!