析构函数是类的一种特殊方法,它会析构或删除对象,并在对象超出范围时自动执行。对象在以下情况下超出范围:

  • 包含对象的函数结束。
  • 程序结束。
  • 包含局部对象变量的块结束。
  • 为对象调用删除运算符unset($obj)。

创建析构函数

PHP __destruct() 函数是一个保留的内置函数,也称为类析构函数。当对象超出范围时,它会自动执行。请注意,它以两个下划线 (__) 开头。一个类只能有一个析构函数。当类中未指定析构函数时,编译器会生成默认析构函数并将其插入到代码中。

语法

function __destruct() {
  statements;
} 

示例:

在下面的示例中,创建了一个名为person的类。还创建了构造函数和析构函数。析构函数在删除对象之前打印一条消息,并在对象超出范围时自动调用(程序在此示例中结束)。

<?php
class person {
  private $name;
  private $city;
  function __construct($name, $city) {
    $this->name = $name;
    $this->city = $city;
    echo $this->name." lives in ".$this->city.".\n";   
  }
  function __destruct() {
    echo "Destructor invoked for: ".$this->name."\n";
  }   
};

$p1 = new person('John', 'London');
$p2 = new person('Marry', 'New York');
?> 

上述代码的输出将是:

John lives in London.
Marry lives in New York.
Destructor invoked for: Marry
Destructor invoked for: John 

再看一个使用unset($obj) 删除对象的例子。

<?php
class person {
  private $name;
  private $city;
  function __construct($name, $city) {
    $this->name = $name;
    $this->city = $city;
    echo $this->name." lives in ".$this->city.".\n";   
  }
  function __destruct() {
    echo "Destructor invoked for: ".$this->name."\n";
  }   
};

$p1 = new person('John', 'London');
$p2 = new person('Marry', 'New York');
echo "执行一下1\n";
unset($p1);
echo "再执行一下2\n";

?> 
输出结果如下:
John lives in London.
Marry lives in New York.
执行一下1
Destructor invoked for: John
再执行一下2
 Destructor invoked for: Marry 
我们看到p1对象是使用删除方法调用的析构函数,p2对象是在程序结束时调用的析构函数.