Wednesday, December 9, 2009

Constructors and Destructors

Constructors and Destructors are special methods that automatically called when every object is created or destroyed. So the idea is whenever object created stop constructing it and perform the constructor method and whenever we destroy an object, stop and do the destruction method.+

Constructors is more useful,its idle for any initializations,that a object may need before its actually going to be used


In PHP4 Constructors method have the same name as the class


class table{
function Table{
//a PHP4 constructor
}
}

In PHP5 its use as
class table{
function_construct{
//a PHP5 constructor


class Table{
public $legs;

function __construct(){
$this->legs=4;
}
}

$table= new Table();
echo $table->legs;
echo "
";
?>


another example:

class Table{
public $legs;
static public $total_tables=0;

function __construct($leg_count=4){
$this->legs=$leg_count;
Table::$total_tables++;
}
function __destruct(){
Table::$total_tables--;
}
}

$table= new Table();
echo $table->legs;
echo "
";

echo Table::$total_tables . "
"; //1
$t1=new Table(5);
echo Table::$total_tables . "
";
$t2=new Table(6);
echo Table::$total_tables . "
";
?>
Constructors and destructors do not have return types nor can they return values.
References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
Constructors cannot be declared with the keyword virtual.
Constructors and destructors cannot be declared static, const, or volatile.
Unions cannot contain class objects that have constructors or destructors

Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.

source:lynda.com

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off