Constructor & Destructor
Constructor

Constuctor is a function. But this function is called automatically when we create object.

There are two way to create constructer:-

<?php
class class_name
{
function class_name()
{

}
}

$obj=new demo();
?>

<?php
class class_name
{
function __construct()
{

}
}

$obj=new demo();
?>

use class name for create constructor use __construct keyword to create constructor


Constructor has two type
1. Default Constructor
2. Parameter Constuctor

Example 1:-

Create constructor by __construct function(Default Constructor).

<?php
class demo
{
function __construct()
{
echo "welcome";
}
}
$obj=new demo();
?>

Output:-
welcome

Example 2:-

Create consturctor by class name(Default Constructor).

<?php
class demo
{
function demo()
{
echo "This is constutor";
}
}
$obj=new demo();
?>

Output:-
This is constutor

Example 3:-

We create parameterized constructor. We are just passing value into the object. and value is storing in object.

<?php
class demo
{
var $message;
function __construct($msg)
{
$this->message=$msg;
}
}

$obj=new demo('welcome');
echo $obj->message;
?>

Output:-
welcome

Destructor Destrutor is a function. this function is called automatically when we exit from programme. this function destroy object from the memory. Example 5:-

test by som

Example 4:-

Adding two value by using parameterized constructor.

<?php
class demo
{
private $z;
function demo($x,$y)
{
$this->z=$x+$y;
}
function show()
{
echo $this->z;
}
}
$obj=new demo(5,6);
$obj->show();
?>

Output:-
11

Destructor

Destrutor is a function. this function is called automatically when we exit from programme.

this function destroy object from the memory.

Example 5:-

<?php
class demo
{
function __construct()
{
echo "Object Created";
}
function __destruct()
{
echo "Object Destory";
}
}
$obj=new demo();
?>

Output:-
Object Created Object Destory


Previous
Next