PHP - Destructors
A destructor is a special method of a class which destructs or deletes an object and automatically executed when the object goes out of scope. An object goes out of scope when:
- the function containing object ends.
- the program ends.
- a block containing local object variable ends.
- a delete operator is called for an object.
Create Destructor
The PHP __destruct() function is a reserved built-in function also called class destructor. It is automatically executed when the object goes out of scope. Please note that it starts with two underscores (__). A class can have only one destructor. When a destructor is not specified in a class, compiler generates a default destructor and inserts it into the code.
Syntax
function __destruct() { statements; }
Example:
In the example below, a class called person is created. A constructor and destructor are also created. The destructor prints a message before deleting the object and called automatically when a object goes out of scope (program ends in this example).
<?php class person { private $name; private $city; function __construct($name, $city) { $this->name = $name; $this->city = $city; echo $this->name." lives in ".$this->city.".\n"; } function __destruct() { echo "Destructor invoked for: ".$this->name."\n"; } }; $p1 = new person('John', 'London'); $p2 = new person('Marry', 'New York'); ?>
The output of the above code will be:
John lives in London. Marry lives in New York. Destructor invoked for: Marry Destructor invoked for: John