What is a destructor in PHP?

In PHP, a destructor is a special type of method or function within a class.

It is automatically called when an object is destroyed or goes out of scope or the script is stopped or exited.

It is defined by using the __destruct() method name.

It will be automatically call the function at the end of the script.

It is typically used to perform cleanup tasks like closing files or database connections before an object is destroyed.

 

Example 1
<?php
class Car {
  public function __construct() {
      echo "Constructor called"."<br>";
  }
  public function __destruct() {
      echo "Destructor called";
  }
}
$obj = new Car(); // Output: Constructor called
unset($obj);         // Output: Destructor called
?>

 

Example 2
<?php
class Car {
public $name;
public $color;
function __construct($name) {
  $this->name = $name;
}
function __destruct() {
  echo "My Car name is : {$this->name}.";
}
}
$obj = new Car("Thar");
?>

 

Example 3
<?php  
  class car{  
  public function car(){  
     echo "User defined constructor1"."<br>";  
     }  
  }  
  class car2 extends car{  
  public function __construct(){  
     echo parent::car();  
     echo "User Defined Extended constructor2"."<br>";  
  }  
  public function __destruct(){  
    echo "Destroy";  
  }  
}
$obj= new car2();
?>  


Prev Next