Introduction
The constructor and destructor is a feature of Object Oriented Programming (OOP). And this concept is implemented in PHP5. Now in this article, I explain "constructor" and "destructor" separately.
Constructor
The constructor is an "OOP" feature. PHP 5 has OOP capability and gives the authority to developers to declare a constructor method for classes. I will first explain what a constructor is. The answer is "A constructor is a special type of method that is automatically called when you create a new instance of the class". The OOP constructor has a number of advantages, they are:
- Constructors can accept parameters, that are assigned to specific object fields at creation time.
- Constructors can call class methods or other functions.
- Class constructors can call on other constructors, including those from the parent class.
Example
In the following code, the parent class (in other words Myclass) has a constructor. It will not be called implicitly because its sub class (in other words Baseclass) defines a constructor (in PHP the parent class constructor is not called implicitly if the child class defines a constructor). Whenever an object of the child class is created. The sub class constructor will be called automatically.
<?php
class Myclass
{
function __construct()
{
print "Parent class constructor.</br>";
}
}
class Baseclass extends Myclass
{
function __construct()
{
parent::__construct();
print " Child Class constructor\n";
}
}
$obj = new Myclass();



Nitin BhardwajPosted Feb 4, 2013, 9:00 AM
Oky Thank u Sharad
Sharad GuptaPosted Feb 4, 2013, 8:12 AM
Hi Nitin , if you want to implement copy constructor in PHP,then you can use clone method to implement copy constructor facility in PHP. <?php class Myclass { static $instances=0; public $instance; function __construct() { $this->instance=++self::$instances; } function __clone() { $this->instance=++self::$instances; } } class Baseclass { public $object1; public $object2; function __clone() { $this->object1=clone $this->object1; } } $obj = new Baseclass(); $obj->object1=new Myclass(); $obj->objec21=new Myclass(); $obj2=clone $obj; echo "<pre>"; print("Orignal object:\n"); print_r($obj); print("clone object:\n"); print_r($obj2); ?>
Nitin BhardwajPosted Feb 4, 2013, 5:43 AM
Hi Sarad, Can we create copy constructor in PHP?
Sharad GuptaPosted Feb 1, 2013, 7:33 AM
thanks Prabhakar
Prabhakar MauryaPosted Feb 1, 2013, 4:44 AM
Nice Explain...