i

PHP Tutorial

PHP-Constructor/Destructor

Like other languages, Constructor allows us to initialize the properties of an object when you create it. You can use constructor in PHP by using __construct() function that starts with two underscores. PHP calls the function automatically whenever an object is created from a class and you can also define parameters for this function. It saves our time and effort to call a function example to set the values for the properties.

For example:

class Cars {
  public $name;
  public $color;

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

$Mercedes = new Cars("Mercedes", "red");
echo $Mercedes->get_name();
echo "
";
echo $Mercedes->get_color();
?>

The __construct() function runs with the name and color attribute specified while creating the object. Set function runs automatically and sets the value for the newly created object.

A destructor is used when the script is stopped, or you exit from the script and objects are destructed. You can use __destruct() function to let PHP automatically call the function at the end of the script to destruct the object.

class Cars {
  public $name;
  public $color;

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

$Swift = new Cars("Swift");
?>

We have only created the object with the name value, but the construct function and destruct function will run automatically and print the output as below:

The Car name is Swift.