Constructors and Destructors in php

Constructor and Destructors Automatically initialized when an object is created and destroyed

Constructors called automatically when the object is created

Syntax

void __construct($args)

Example 1

<?php
class PHP
{
      
    public function __construct()
    {
        echo "Hi, i am Constructors";        
    }
}
$object = new PHP();
?>
//Output
Hi, i am Constructors

Example 2 - Pass Parameters

<?php
class Language
{
    public $lang = "javascript";
    
    public function __construct($l)
    {
        $this->lang = $l;
    }
}
$object = new Language("PHP");
echo $object->lang;
?>
//Output
PHP

Destructors

Syntax

void __destruct (void)

Example

<?php
class Language
{
    public $lang = "js";
    public function __construct($l)
    {
        echo "Hi i am Constructors!";    
        $this->lang = $l;
    }
    
    public function __destruct()
    {
        echo "I am Destructors!";
    }
}
$object = new Language("PHP");
echo $object->lang;
?>
//Output
Hi i am Constructors! 
PHP
I am Destructors!

Parent Constructors and Destructors

<?php
class Test extends Language
{
    function __construct()
    {
        parent::__construct();
    }
    function __destruct()
    {
        parent::__destruct();
    }
}
?>