php 什么时候在php中使用析构函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2618472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
when to use destructor in php?
提问by never_had_a_name
what is the main purpose of a destructor?
析构函数的主要目的是什么?
could you give any examples of what i might want to run when a object is deleted?
你能举例说明删除对象时我可能想要运行的内容吗?
采纳答案by Matt
It gives the object an opportunity to prepare to be killed. This could mean manual cleanup, state persistence, etc.
它让对象有机会准备被杀死。这可能意味着手动清理、状态持久化等。
For example, a Model may want to save all of its current properties back into the database.
例如,模型可能希望将其所有当前属性保存回数据库。
Or, a Database object itself might want to close the socket it is using to communicate to a database server.
或者,一个数据库对象本身可能想要关闭它用来与数据库服务器通信的套接字。
回答by Byron Sommardahl
So, you probably know what a constructor does. If a constructor sets up, a destructor cleans up. Here's an example from the PHP site:
因此,您可能知道构造函数的作用。如果构造函数建立,析构函数将清理。这是来自 PHP 站点的示例:
<?php
class my_class {
public $error_reporting = false;
function __construct($error_reporting = false) {
$this->error_reporting = $error_reporting;
}
function __destruct() {
if($this->error_reporting === true) $this->show_report();
unset($this->error_reporting);
}
?>
Here's the linkto the PHP documentation on the subject.
回答by grossvogel
Say I have a Resultclass that is a wrapper (implementing Iterator, among other niceties) for the mysqli_resultobject. When I destroy one of my Resultobjects, I want to be sure to call the free()method on the mysqli_resultobject to reclaim the memory it was using. So I do that in the destructor of my Resultclass.
假设我有一个Result类是mysqli_result对象的包装器(实现Iterator,以及其他细节)。当我销毁我的一个对象时,我想确保调用该对象上的方法以回收它正在使用的内存。所以我在班级的析构函数中这样做。Resultfree()mysqli_resultResult
回答by zloctb
Reference for book
书籍参考
Destructor often use for close DB connections and fclose ()for fopen()connection in class
析构函数经常使用近距离DB连接,并fclose ()为fopen()类连接

