CONSTRUCTOR-DESTRUCTOR

Constructor Functions :

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ){

$this->price = $par1;

$this->title = $par2;

}

Destructor :

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.

Example for constructor & Destructor :

<?php

class example

{

function __construct()

{

echo “constructor is called & object is created”;

echo “<br>”;

}

Function __destruct()

{

echo “destructor is called & object is free”;

}

}

$obj=new example();

?>

How to call parent class constructor parent::__construct(); :

<?php

class BaseClass {

function __construct() {

print “In BaseClass constructor\n”;

}

}

class SubClass extends BaseClass {

function __construct()

{

parent::__construct();

print “In SubClass constructor\n”;

}

}

//$obj = new BaseClass();

$obj = new SubClass();

?>