Reader Level:
ARTICLE

Constructor and Destructor in PHP

Posted by Sharad Gupta Articles | PHP January 29, 2013
In this article I explain how to create a constructor and release memory by a destructor.
  • 0
  • 0
  • 5018

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();

$obj = new Baseclass();

 

?>

Output

constructor-in-php.jpg

Destructor

The destructor is another feature of "OOP". The destructor concept was introduced in PHP5 and it is conceptually similar to that of other object oriented languages. The destructor method will be called as soon as there are no other references to a particular object or when the object has been explicitly destroyed.

Example

<?
php
class
MyClass
{

function __construct()
{

print "In constructor";

$this->name = "MyClass obj explicity";

}

 

function __destruct()
{

print "Destroying " . $this->name . "\n";

}

}

 

$obj = new Myclass(); 

?>

Output

destructor-in-php.jpg

COMMENT USING

Trending up