If you have already register Login here.
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.
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.
<?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!
© 2023 Easy To Learning. All Rights Reserved | Design by Easy To Learning