What are constructor and destructor in PHP ?

devquora
devquora

Posted On: Mar 24, 2020

 

    1 Answer Written

  •  devquora
    Answered by Anug Verma

    In PHP there are two special functions known as constructor and destructors which are used for creating and destroying an object respectively. A constructor is used mostly for sending parameters and creating any new object.

    Example

    class Animal
    {
         public $name = "No-name animal" ;
    
         public function _construct() 
         {
                  echo "I 'm alive!";
         } 
    } 
    
    

    For constructing a new object in the above code we will use the Coding line

    $animal = new Animal();

    The result that we will get is

    <?php
    class Animal
    {
         public $name = "No-name animal" ;
    
         public function _construct($name) 
         {
               $this- >name = $name;
         } 
    } 
    
    $animal = new Animal ( "Bob the Dog") ;
    echo $animal- >name;
    ? >
    

    In the case of destructor

    For the same example, if you want to dispose of an object then you need to do it manually. The object will get destroyed automatically which is not needed.

    <?php
    class Animal
    {
         public $name = "No-name animal" ;
    
         public function _construct($name) 
         {
              echo "I 'm alive!";
              $this- >name = $name;
         } 
         
         public function _destruct () 
        {
                 echo "I 'm dead now : (" ;
        } 
    } 
    
    $animal = new Animal("Bob") ;
    echo "Name of the animal: " . $animal- >name; 
    ? >
    
    

Related Questions

Please Login or Register to leave a response.

Related Questions

PHP Interview Questions

What is T_PAAMAYIM_NEKUDOTAYIM in PHP?

T_PAAMAYIM_NEKUDOTAYIM is scope resolution operator used as :: (double colon) .Basically, it used to call static methods/variables of a Class...

PHP Interview Questions

What is the difference between == and === operator in PHP ?

In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type...