×
☰ See All Chapters

PHP construct and destruct

  • __construct() and __destruct() are the special functions of a class. PHP will automatically call construct function when object is created for a class and automatically call destruct function at the end of the script when objects are destroyed.  

  • Both construct and destruct functions starts with two underscores (__). 

  • __construct() function can be used to initialize the object properties, while __destruct() function can be used to release the object level resources before destruction of object before script execution completion.   

  • __construct() function can specify parameters, When parameters specified then while creating object using new keyword arguments should be passed.   

  • __destruct() function does not allow parameters.         

  • When no __construct and __destruct() functions added, PHP will create default functions without parameters. 

  • __construct() and __destruct() functions will not allow access specifiers. 

__construct() function syntax without parameters

function __construct() {

}

 

Syntax to create objects having  __construct() function without parameters

$object_reference_variable = new ClassName();

__construct() function syntax with parameters

function __construct($pmtr1, $pmtr2, $pmtr3 ...) {

}

 

Syntax to create objects having  __construct() function with parameters

$object_reference_variable = new ClassName(value1, value2, value3);

PHP __construct and __destruct example

<?php

class Box {

   public $width;

   public $height;

   public $depth;

   function __construct($width, $height, $depth) {

       echo "construct called </br>";

       $this->width = $width;

       $this->height = $height;

       $this->depth = $depth;

   }

   public function volume () {

       return  $this->width *  $this->height *  $this->depth;

   }

   function __destruct () {

       echo "destruct called";

   }

}

$box = new Box(10, 20, 30);

echo "Volume of Box: ". $box->volume() . "</br>";

?>  

php-construct-and-destruct-0
 

All Chapters
Author