In the previous article, we have covered the basic concepts of a class and objects. In this PHP tutorial, you will learn constructors and destructors in the PHP class.

What is a Constructor and Destructor in PHP class?

Constructor

As the name suggests, a construct constructs an object. The real definition of a constructor is, it initializes the object of the class.

How to declare the constructor in PHP?

To declare a constructor in PHP, use double underscore (__) along with the word construct. Make sure that the name of the constructor must be “constructor”.

For instance

<?php
class Pet {
  public $nick_name;
  public $color;

  function __construct($name) {
    $this->nick_name = $name;
  }
  function get_name() {
    return $this->nick_name;
  }
}

$cat = new Pet("Cat");
echo $cat>get_name();
?>
  • In the above example, we create a constructor using double underscores.
  • We create an object, which use the the constructor automatically and intialize it with Cat.
  • We don’t need to call the set_name function for setting the name in the cat object.

So, it is clear from the above discussion about the constructor makes it easy to initialize the object and does not require any setter function to do so.

More example about PHP Constructor

<?php
class Pet {
  public $nick_name;
  public $color;

  function __construct($name, $color) {
    $this->nick_name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->nick_name;
  }
  function get_color() {
    return $this->color;
  }
}

$cat = new Pet("Cat", "Brown");
echo $cat->get_name();
echo "<br>";
echo $cat->get_color();
?>
  • In the above example, we create a constructor with two parameters and initialize the nick_name and color attributes of the class with these params.
  • We create new cat object and pass the two parameters required by the construtor. Make sure, to create an object, it requires the number of paramters according to the constructor of the class to which it belongs.
  • After creating the object, we tested it by calling get_name and get_color setters of the class. It will output the name of the cat object as “cat” and its color as “brown”.

You can find the reference to the official constructor documentation in PHP here.

Important concept about constructor

OOP allows the mechanism of inheritance by which a child class can extend a base class or parent class. We will cover it in detail, as for now, we just need its description to understand the concept. If the child class is extending the parent class and wants to call the parent class constructor in its own constructor, simply use parent::construcor_name inside its constructor.

If the child class does not contain its constructor, then the constructor of base or parent class is inherited as a normal function if not declared as private.

How to declare default parameter in the constructor?

As you read above that a constructor can have multiple parameters, which are provided while creating the object using it. But, if you want to make parameters not mandatory to provide while creating the object, you can set a default value of the constructor parameter. For instance.

public function __construct(int $x, int $y = 0) {
        $this->x = $x;
        $this->y = $y;
    }
  • In the above example, $y is assigned a default value of 0.
  • If the object $obj = new class (2) is created, the default value of y will set to 0 by the constructor.

Destructor

The main purpose of the destructor is to destroy or remove the object from the memory after the execution of the program is stopped or the process is terminated.

In PHP, you don’t need to call the destructor to free the memory taken by the objects because it automatically calls the destructor to remove all the objects after the script stops its execution.

However, you can declare destructor to print some message which help you to validate or check when the destructor will call and what processing is done inside the destructor.

Look at the following example to declare destructor in PHP

<?php
class Pet {
  public $nick_name;
  public $color;

  function __construct($name) {
    $this->nick_name = $name;
  }
  function __destruct() {
    echo "The Pet is {$this->nick_name}.";
  }
}

$cat= new Pet("cat");
?>
  • In the above example. we create an object using the constructor.
  • We print some message inside the desctruct method.
  • Test by running the script. Observe the output of the script for the message inside the destruct.

Another example of destructor

<?php
class Pet {
  public $nick_name;
  public $color;

  function __construct($name, $color = "brown") {
    $this->name = $nick_name;
    $this->color = $color;
  }
  function __destruct() {
    echo "The Pet is {$this->nick_name} and its color is {$this->color}.";
  }
}

$cat =  new Pet("Cat");
?>
  • In the above example, we use the constructor to intialize the object. Observer that the constructor accepts two parameters but we are passing it one because constructor use the default value of color and assign in to the color attribute of the object.
  • We print some message inside the desctruct method along with the nick_name and color.
  • Observe the output of the script at the termination point.

Also, you can call the destructor to perform some tasks that need to be done at the time of termination of the script. Like closing the Database connections or external file stream objects.

Destructors look simple according to the implementation point of view, but they play a vital role to keep the memory safe from leakage.

If any object resides in the memory after the termination of the PHP script, it causes memory leakage and can cause serious problems, especially for large-scale applications.

You can find the reference to the official destructor documentation in PHP here.