PHP 析构方法 __destruct() 允许在销毁一个类之前执行执行析构方法。
析构方法
与构造方法对应的就是析构方法,析构方法允许在销毁一个类之前执行的一些操作或完成一些功能,比如说关闭文件、释放结果集等。析构函数不能带有任何参数,其名称必须是 __destruct() 。
语法:
function __destruct() { ...... }
举个例子:
class person { public $name; //定义一个析构方法 public function __construct() { echo "good bye".$this->name; } }class Person { public $name; //定义一个构造方法 public function __construct($name) { $this->name = $name; } //再定义一个析构方法 public function __destruct() { echo "good bye ".$this->name; } } $name = 'lightWay'; $person = new Person($name);
再次运行该例子,输出:
good bye lightWay
让我们把代码放在html当中:
<html> <head> <title>test</title> </head> <body> <?php class Person { public $name; //定义一个构造方法 public function __construct($name) { $this->name = $name; } //再定义一个析构方法 public function __destruct() { echo "good bye ".$this->name; } } $name = 'lightWay'; $person = new Person($name); ?> </body> </html>
运行在看看浏览器源码:
<html> <head> <title>test</title> </head> <body> </body> </html> good bye lightWay
我们会发现更为诡异的现象,没错,析构方法输出的内容在html标签外边,很明显,这压根不是我们代码中的执行过程,这也侧面说明了,析构方法是php脚本运行结束后php的资源处理过程
在看看销毁的顺序:
class Person { public $name; //定义一个构造方法 public function __construct($name) { $this->name = $name; } //再定义一个析构方法 public function __destruct() { echo "<br />good bye ".$this->name; } } $name = 'lightWay'; $person1 = new Person($name); $name = 'tom'; $person2 = new Person($name); $name = 'bob'; $person3 = new Person($name); $name = 'jim'; $person4 = new Person($name); $name = 'john'; $person5 = new Person($name); unset($person2);//提前销毁$person变量
再次运行该例子,输出:
good bye tom good bye john good bye jim good bye bob good bye lightWay可以看得出来,销毁顺序是是变量声明的倒序,提前unset就会提前进入析构流程提示
- 和构造方法一样,PHP 不会在本类中自动的调用父类的析构方法。要执行父类的析构方法,必须在子类的析构方法体中手动调用 parent::__destruct() 。
- 试图在析构函数中抛出一个异常会导致致命错误。
- 在 PHP4 版本中,构造方法的名称必须与类名相同,且没有析构方法。