Destructor in PHP :
Destructor in PHP is similar to other oops(object oriented programming) concept.
PHP Destructor is handled by the Garbage Collector which always focus over object when there are no needed of object then it automatically destroyed.
Destructor function are inverse of
Constructor. The method name of Destructor in php is differ from Constructor method name and it can't take any arguments like constructor.
Destructor function name in PHP is `__destruct()`.
Constructor is involved when objects are created and Desctructor is involved when object are deleted.
Here is a example of destructor :
- class Bird
- {
- public $bird_name = "No any birds for now";
-
- public function __construct($bird_name)
- {
- echo "I'm alive!";
- $this--->bird_name = $bird_name;
- }
-
- public function __destruct()
- {
- echo "I'm dead now :(";
- }
- }
- $bird = new Bird("Sparrow is bird");
- echo "Name of the bird: " . $bird->bird_name;
- ?>
- Output :
- I'm alive!Name of the bird: Sparrow is birdI'm dead now :(
class Bird{ public $bird_name = "No any birds for now"; public function __construct($bird_name) { echo "I'm alive!"; $this--->bird_name = $bird_name; } public function __destruct() { echo "I'm dead now :("; }}$bird = new Bird("Sparrow is bird");echo "Name of the bird: " . $bird->bird_name;?>Output :I'm alive!Name of the bird: Sparrow is birdI'm dead now :(// so as we seen, __destruct is called when object is removed or destroyed.