Destructor in PHP With Example - Informatic Point

Destructor in PHP With Example

Destructor in PHP. A Destructor is a function used for destroying the object instance that was performed by a constructor for a provided class, as a part of its functional specialty. At any moment a constructor is used in a PHP program, it is not compulsory to have a destructor function to complement its functionality. But it is thought of as a good method to have a destructor in the Code where a constructor is named for. Also, this process is not specifically called for execution, instead, it is performed when the control doesn’t find any more functional references to the constructor method.

<?php
class <Write_Class_Name> {
// Here we Declaring a constructor
function __construct() {
// To initialize required properties
}
// Here we Declaring a destructor
function __destruct() {
// Now we remove reference of an object
}
}
?>

Working of Destructor in PHP

Destructor is essentially controlled by the Garbage Collector which realizes an object when it is not required anymore. It cannot take any disputes as to its input in contrast to the PHP constructor.

This process is also used for cleaning up sources and to free the memory for accepting more exceeding. Overloading cannot be made with destructors and only a unique destructor can exist in the same class. Another single feature of it is that yet if the script has ended its performance with the help of an exit() command, the destructor will quite be called. This exit() will not provide the extra shutdown methods from ending.

Example

This is an easy instance where we are building a basic constructor function and then slaying the same by calling the destructor function.

<?php
class Destructor
{
function __construct() {
print "It is Inside constructor\n";
}
function __destruct() {
print "It Is Destroying the class " . __CLASS__ . "\n";
}
}
$obj = new Destructor();
?>
Output
It is Inside constructor
It Is Destroying the class Destructor

Advantages of Destructor in PHP

  • Destructors assist in clearing up memory allocation so creating certain the needed space is present for newly formed objects by the constructor or clearing up support for any other work.
  • Assures that all the work runs efficaciously since it takes care of the cleanup process.
  • In instances where various PHP variables and formations are formed, the usage of destructors will assist limit memory slips by delivering internal resources.
  • It needs the care of both Static and local variables.

Conclusion

As we noticed, destructors obtaining the specific inverse of constructors are used to defeat an object after its practice is performed and are not needed more in the program. Thus assuring that it cleans up undesired resources enabling space for coming resources. This is performed by maintaining the __destruct) the function which will be described by PHP automatically at the script performance.