PHP constructor automatically calls whenever a new object is created while the PHP destructor i.e __destruct() function executes automatically when the object is destroyed.
PHP constructor function 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 __destruct()
method is executed automatically when the object is destroyed.
Please 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");
?>
__destruct()
method will be called at the end of the execution of the script.