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?
Say I have a Result
class that is a wrapper (implementing Iterator, among other niceties) for the mysqli_result object. When I destroy one of my Result
objects, I want to be sure to call the free()
method on the mysqli_result
object to reclaim the memory it was using. So I do that in the destructor of my Result
class.
Reference for book
Destructor often use for close DB connections and fclose ()
for fopen()
connection in class
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
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 link to the PHP documentation on the subject.
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.