Constructor and Destructor in PHP
What is Constructor?
Generally Constructor is one kind of method which has same name as class name.its used to initialize variable of object at the time of declaration.Constructor is basically OOPs concept in PHP.
In PHP4, Constructor is the method which have same name as class name whereas in PHP5,We have magic method say __construct to call constructor.The constructor gets called automatically for each object that has got created.Its may or may not take parameters.
NOTE: Constructor should be defined in PUBLIC class.
Basic Example
|
1 2 3 4 5 6 7 8 9 10 |
class Test
{
function __construct()
{
echo 'Within Constructor';
}
}
$obj = new Test();
// OUTPUT: Within Constructor |
Parameterized Constructor
Parameterized constructor means we pass parameter within in constructor method.Constructor can take arguments so let’s see by example
|
1 2 3 4 5 6 7 8 9 |
class const_over
{
function __construct($name)
{
echo $name;
}
}
$obj = new const_over("Bhumi");// Constructor called implictly
// OUTPUT: // Bhumi |
NOTE: The constructor is non-static member function.
What is Destructor?
The destructor gets called for each object of class that is destroy.It appears as member function of each class whether its defined or not.For destructor, we also have magic method called __destruct in PHP.
The destructor can used to guarantee a proper deinitialize the object of class and free up the resources acquired by object.Destructor is also a member function of a class.
Now let’s see mysql connect code which uses both Constructor and destructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Construct_cls {
var $dbHost,
$dbUser,
$dbName,
$dbPass,
$conn,
$sql,
$rs;
function __construct()
{
$this->dbHost = 'localhost';
$this->dbUser = 'root';
$this->dbPass = '';
$this->dbName = 'test';
$this->conn=mysql_connect($this->dbHost,$this->dbUser,$this->dbPass);
$this->db=mysql_select_db($this->dbName);
}
function runQuery()
{
$this->rs=mysql_query($this->sql);
return $this->rs;
}
function __destruct()
{
mysql_close();
}
}
$obj = new Construct_cls();
$obj->sql = "SELECT * FROM category";
$result = $obj->runQuery();
$data = mysql_fetch_array($result);
print_r($data); |








Recent Comments