PHP constructor automatically calls whenever a new object is created while the PHP destructor (php __destruct()) function executes automatically when the object is destroyed. The constructor in PHP is called when the object is created.
The magic method __construct()
is known as a constructor that is automatically called whenever a new object is created.
Please keep in mind that the construct function starts with two underscores (__)
.
The __construct()
method should always have public visibility.
When you don't have a constructor (or you have a constructor without arguments), you can create the object from the class without parentheses.
class House{}
$house = new House;//object
Source Code
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
But, if you have a constructor with arguments, you should send the values for those arguments when you create them.
Source Code
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
The destructor in php (__destruct()
) is executed automatically when the object is destroyed. Keep in mind that the destructor function starts with two underscores (__)
.
Source Code
<?php
class House {
public $name;
public $color;
public function __construct($name, $color) {
$this -> name = $name;
$this -> color = $color;
}
public function __destruct() {
echo "The color of the {$this -> name} is {$this -> color}";
}
}
$blackHouse = new House("John's House", "black");
?>
In the above example, the __destruct()
method will be called at the end of the execution of the script.
I hope that you have understood the PHP class constructor as well as the PHP class destructor. Basically, it comes into action when a new object is created or destroyed, respectively. It is widely used during web development. Therefore, you must understand the constructor and the destructor.