Constructor and Destructor
What is Constructor
The Constructor is a class function called automatically when an instance is created for that class. The Destructor is a function that is invoked when the class instance is destroyed. In PHP, the constructor and the destructor are defined by using the magic functions __construct() and __destruct() respectively. The following code shows an example with the class constructor used to initialize its private property.
Constructor types:
- Default Constructor: It has no parameters, but the values to the default constructor can be passed dynamically.
- Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.
- Copy Constructor: It accepts the address of the other objects as a parameter.
Example Of Constructor
<?php
class Car{
private $modal;
function __construct() {
$this->modal = array("Alto","I10", "Audi");
}
function getAllModal() {
foreach($this->modal as $modal) {
print $modal . "<br/>";
}
}
}
$carObj= new Car();
echo "<b>All Modals:</b><br/>";
$carObj->getAllModal();
?>
What is Destructor:
Destructor is also a special member function which is exactly the reverse of the constructor method and is called when an instance of the class is deleted from the memory.
Example Of Destructor
<?php
class Car{
private $modal;
function __construct() {
$this->modal = array("Alto","I10", "Audi");
}
function getAllModal() {
foreach($this->modal as $modal) {
print $modal . "<br/>";
}
}
function __destruct(){
echo "destroying " . $this->name . "\n";
}
}
$carObj= new Car();
echo "<b>All Modals:</b><br/>";
$carObj->getAllModal();
?>
Output:
Alto
In the constructor, destroying Class object!
