Introduction
In object oriented programming terminology, constructor is a method defined inside a class is called automatically at the time of creation of object. Purpose of a constructor method is to initialize the object. In PHP, a method of special name __construct acts as a constructor.
Syntax
__construct ([ mixed $args = "" [, $... ]] ) : void
Constructor example
This example shows that constructor is automatically executed when object is declared
Example
<?php
class myclass{
function __construct(){
echo "object initialized";
}
}
$obj=new myclass();
?>Output
This will produce following result. −
object initialized
Constructor with arguments
Class properties are initialized by constructor with arguments
Example
<?php
class rectangle{
var $height;
var $width;
function __construct($arg1, $arg2){
$this->height=$arg1;
$this->width=$arg2;
}
function show(){
echo "Height=$this->height Width=$this->width";
}
}
$obj=new rectangle(10,20);
$obj->show();
?>Output
This will produce following result. −
Height=10 Width=20
Constructor in inheritance
If the parent class has constructor defined in it, it can be called within child class's constructor by parent::__construct. However, if child class doesn't define a constructor, it inherits the same from is base class.
Example
<?php
class a{
function __construct(){
echo "this is a constructor of base class\n";
}
}
class b extends a{
function __construct(){
parent::__construct();
echo "this a constructor class b\n";
}
}
class c extends a {
//
}
$a=new a();
$b=new b();
$c=new c();
?>Output
This will produce following result. −
this is a constructor of base class this is a constructor of base class this a constructor class b this is a constructor of base class
Destructor
Destructor is a method automatically as soon as garbage collector fins that a particular object has no more references. In PHP, destructor method is named as __destruct. During shutdown sequence too, objects will be destroyed. Destructor method doesn't take any arguments, neither does it return any data type
Example
<?php
class myclass{
function __construct(){
echo "object is initialized\n";
}
function __destruct(){
echo "object is destroyed\n";
}
}
$obj=new myclass();
?>Output
This will show following result
object is initialized object is destroyed