Constructor and Destructor in PHP


Constructor and Destructor:


Constructor is special type of method because its name is similar to class name. Constructor automatically calls when object will be initializing.


Example:

<?php

class Animal

{

   public $name = "No-name animal";

   public function __construct($name)

   {

       $this->name = $name;

   }}

$animal = new Animal("I Section");

echo $animal->name;

?>

Output: I Section


Declaring the constructor with parameters is just like declaring a regular function, and passing the parameter(s) is much like calling a regular function, but of course with the "new" keyword that we introduced earlier. A constructor can have as many parameters as you want.


Destructor:

A destructor is called when the object is destroyed. In some programming languages, you have to manually dispose of objects you created, but in PHP, it's handled by the Garbage Collector, which keeps an eye on your objects and automatically destroys them when they are no longer needed. Have a look at the following example, which is an extended version of our previous example:

<?php

class Animal1

{ /* Destructor */

   public $name = "No-name animal";

   public function __construct($name)

   {

       echo "I'm alive!";    

       $this->name = $name;

   }    

   public function __destruct()

   {

       echo "I'm DESTROY NOW :(";

   } }

$animal1 = new Animal1("Raja  ");

echo "Name of the person: " . $animal1->name;

?>


Output: I'm alive!Name of the person: Raja I'm DESTROY NOW 🙁

Custom Search

%d bloggers like this: