pTutorial

New way to learn PHP

PHP 5 Destructor

Destructor

Destructor method is opposite of the constructor function that means it destroys an object. You can explicitly create a destructor method by naming it __destruct(). Destructor method will be invoked automatically by PHP at the end of the execution of your script.

You can declare a destructor anywhere of your script, It's execute at the end, that means all the memory resources are freed at the end.

Use of destructor

The destructor can still use full for performing certain actions such a flushing a resource or logging information on object destructor.

PHP5 destructor

function __destruct()
{ 
echo " Object Destroyed.";
}

Example of destructor

<?php

class DesExample 
{
	
    function __destruct() {
       print "Destroying object....... 
"; } } $obj = new DesExample(); echo "It execute before the destructor"; ?>

Output

It execute before the destructor
Destroying object.......

In the above example, echo construct executes before the destructor because destructor executes at last.

Example of destructor

<?php

class Fact
{ 
private $result = 1; 
private $number; 
function __destruct()
{ 
echo " Object Destroyed.";
   }

function  Fact($num) 
{ 
$this->number = $num; 
for($i=2; $i<=$num; $i++) 
{ 
$this->result *= $i; 
} 
}
 function display() 
{ 
echo "Factorial of {$this->number} is {$this->result}. "; 
}
}
$factorial = new Fact(5);
$factorial->display();

?>

Output

Factorial of 5 is 120. Object Destroyed.

In this example, we are creating fact class and Initializing the value of these data members by using the constructor function. And after that create an object pass the argument to the constructor and call the display method with the help of the object named $obj. At the end destructor will execute and remove all the data of factorial object.

Download PHP script

Unset function

unset() function is also used to destroy the object. This will remove all of the contents of the object from memory.

Example of destructor using unset function

<?php

class Fact
{ 
private $result = 1; 
private $number; 
function  Fact($num) 
{ 
$this->number = $num; 
for($i=2; $i<=$num; $i++) 
{ 
$this->result *= $i; 
} 
}
 function display() 
{ 
echo "Factorial of {$this->number} is {$this->result}. "; 
}
}
$factorial = new Fact(5);
$factorial->display();
unset($factorial);
//print_r($factorial);


?>

Output

Factorial of 5 is 120.

Download

.

Note: there is no need to use destructors, unless you are using objects that are taking up considerable resources; all variables and objects are automatically destroyed once the script finishes execution.


QUOTES OF THE DAY

The ballot is stronger than bullet.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER