Constructor is specialized method that is contained in class. Constructor will be trigger automatically when an object is created. Constructor is to initialize an object of a class.
Constructor name is identical to the class name. Constructor can take parameter but Constructor has no return type .This is because Constructor returns an object by itself. In PHP version 5 and above the is a Constructor method named _construct (), which the new keyword automatically calls after creating the object. It is usually used to automatically perform initialization such as property initialization.
Eample 1
class student
{
private $name;
public function _constructor($name)
{
$this->name=$name;
}
public function
getname()
{
return $this-name;
}}
Example 2
<? php
class first
{
Function A ( )
{
echo “ This is user defined
constructor”;
}
Function _constructor ( )
{
echo “This is predefined constructor
“;
}
}
$obj= new A ( );
?>
Destructor: The destructor gets called for
each object of class that is destroyed. It appear as member function of
each class whether its define or not. For destructor we also have magic method
called _destruct in PHP. Destructor is also
member of class. It is used to free the memory.
Eample
<?php
Class des
{
function _construct( )
{
echo “ Object is initialize and their property “;
}
function work(
)
{
echo “ now work is going “. “<br>”;
}
function _destruct( )
{
echo “ this object is destroyed automatically”;
}
$obj = new des( );
$obj->work( );
echo is_object
($obj);
?>
Here Video Tutorial of Constructor
Here Video Tutorial of Constructor