Constructor and Destructor

Constructor :

  • PHP 5 provides two ways where you can write a constructor method inside a class.

  • First way is to create a method with the name __construct() inside the class.

  • The second way is to create a method naming exactly the same as class name.

<?php class factorial
{
private $result = 1;
private $num;
function __construct($num)//Construtor
{
$this->num = $num;
for($i=2; $i<=$num; $i++)
{
$this->result*=$i;
}
echo "__construct() executed. ";
}
function factorial($num)
{
$this->num = $num;
for($i=2; $i<=$num; $i++)
{
$this->result*=$i;
}
echo "factorial() executed. ";
}
public function display()
{
echo "factorial of {$this->num} is {$this->result}. ";
}
}
$factorial = new factorial(5);
$factorial->display();
?>
			
Output :
__construct() executed. factorial of 5 is 120. 
			

Destructor :

  • It is similar to constructor method.

  • Destructor method which actually works upon destroying an object.

  • You can explicitly create a destructor method by naming it __destruct().

  • It will be invoked automatically by PHP at the end of the execution of your codes.
$lt;?php class factorial
{
private $result = 1;
private $num;
function __construct($num)
{
$this->num = $num;
for($i=2; $i<=$num; $i++)
{
$this->result*=$i;
}
echo "__construct() executed. ";
}
function factorial($num)
{
$this->num = $num;
for($i=2; $i<=$num; $i++)
{
$this->result*=$i;
}
echo "factorial() executed. ";
}
public function display()
{
echo "factorial of {$this->num} is {$this->result}.</br> ";
}
function __destruct()//Destructor
{
echo " Destroyed. ";
}
}
$factorial = new factorial(5);
$factorial->display();
?>
Output :
__construct() executed. factorial of 5 is 120.
Destroyed.