Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use destructor in php?

Tags:

php

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?

like image 686
never_had_a_name Avatar asked Apr 11 '10 19:04

never_had_a_name


People also ask

When should I use destructor?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

What is the use of constructors and destructors in PHP?

Constructor is involved automatically when the object is created. Destructor is involved automatically when the object is destroyed. Used to initialize the instance of a class. Used to de-initialize objects already existing to free up memory for new accommodation.

What is the benefit of destructor?

Advantages of Destructor in C++It gives a final chance to clean up the resources that are not in use to release the memory occupied by unused objects like deleting dynamic objects, closing of the system handles, used files.

In which case destructor is mandatory?

Destructor function is called automatically when the object goes out of scope. When a class contains dynamic object then it is mandatory to write a destructor function to release memory before the class instance is destroyed this must be done to avoid memory leak.


2 Answers

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.

like image 161
Matt Avatar answered Oct 04 '22 03:10

Matt


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.

like image 26
Byron Sommardahl Avatar answered Oct 04 '22 03:10

Byron Sommardahl