PHP 析构函数

创建于 2024-12-03 / 51
字体: [默认] [大] [更大]

PHP - __destruct 函数

当对象被破坏或脚本停止或退出时,会调用一个析构函数。

如果你创建了一个__destruct()函数,PHP会在脚本结束时自动调用这个函数。

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

下面的例子有一个__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");
?> 亲自试一试 »

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



0 人点赞过