tags:

views:

78

answers:

3

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?

+2  A: 

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.

Matt
- It is also use for cleaning up :D
Hanseh
Also, something to note, __destruct not only gets called with an object is deleted, but also when an object falls out of scope, as well as when the script ends
deadkarma
+1  A: 

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.

grossvogel
+1  A: 

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.

Byron Sommardahl