Monday, March 30, 2009

Constructors and Destructors in php

From php5, constructors method can be declared within class. If you have declared a constructor in a class that the constructor method will be automatically called during creation of an instance of the class. So, you can declare a constructor whenver you think the initialization of an object must needed everytime after an instance is created.

Note that, you have both parent and child constructor corresponding to parent and child table. If you create an instance of the child table, parent constructor is not called implicitly. To call the parent constructor while creating child object, within child constructor you have to call parent constructor explicitly. Constructor is declared by keyword __construct (note that double underscore(__) is prepend before construct) and calling the parent constructor is done by parent::__construct().

As constructor is created for some initialization of the object, destructor comes for to destroy the object. Or in other word destructor is used to release any resources allocated by the object. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Below is an example of using both constructor and destructor.

<?php
class ParentClass {
function __construct(){
echo "This is the parent constructor. ". get_class($this);
echo "<br />";
}
}
class ChildClass extends ParentClass{
function __construct(){
echo "This is the child constructor. ".get_class($this);
echo "<br />";
}
function __destruct() {
echo "Destroying child object ";
}
}
$childInstance=new ChildClass();
?>

And the output on the browser is,

This is the child constructor. ChildClass
Destroying child object

Note that parent constructor is not called with the creation of child instance. In other to do so we have to call it within child constructor as shown below.

<?php
class ParentClass {
function __construct(){
echo "This is the parent constructor. ". get_class($this);
echo "<br />";
}
}
class ChildClass extends ParentClass{
function __construct(){
parent::__construct();
echo "This is the child constructor. ".get_class($this);
echo "<br />";
}
function __destruct() {
echo "Destroying child object. ". get_class($this);
}
}
$childInstance=new ChildClass();
?>

And output is below.

This is the parent constructor. ChildClass
This is the child constructor. ChildClass
Destroying child object. ChildClass

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html

No comments:

Post a Comment