PHP Constructor and Destructor

PHP Constructor

The PHP Constructor function is a special type of function which is called automatically whenever an object is created. It is used to initialise the values of member variables at the time of creation of object. We can use a special function called __construct() to define constructor. The syntax is :
function __construct(parameters) {
  //initializing object properties
}
Example :
function __construct($para1, $para2) {
  $var1 = $para1;
  $var2 = $para2;
}
Now lets see an example :
<?php

class Student {
  var $name;
  var $age;

  function __construct($arg1, $arg2) {
    $this->name = $arg1;
    $this->age = $arg2;
  }

  function showData() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age;
  }

}

$stud = new Student("John", 18);

$stud->showData();

?>
Output :

Name : John
Age : 18

At the above we directly initialised the value of member variables at the time of object creation at line {line number of $stud = new Student("John", 18); }.


PHP Destructor :

The PHP  destructor is used for destroying object reference. A destructor function cleans up any resources allocated to an object once the object is destroyed. It is called automatically when a scripts ends. The syntax of destructor function is :
function __destruct() {
  //clearing object reference
}
Example :
function __destruct() {
  echo "Object Destroyed.";
}
Also note that we don't need to call the destructor function, it will execute automatically at the end of the script.

Example :
<?php

class Student {
  var $name;
  var $age;

  function __construct($arg1, $arg2) {
    $this->name = $arg1;
    $this->age = $arg2;
  }

  function showData() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age . "<br/><br/>";
  }

  function __destruct() {
    echo "Object Destroyed.";
  }
}

$stud = new Student("John", 18);

$stud->showData();

?>
Output :

Name : John
Age : 18

Object Destroyed.


Next Topic :