Home Tutorial Php Phpoop PHP Constructor and Destructor

 
 

Share on Google+Share on Google+
PHP Constructor and Destructor
Posted on: February 18, 2010 at 12:00 AM
Advertisement
In this current tutorial we will study about constructor and destructor of OOP.Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor method is called for every object creation.

PHP Constructor & Destructor:

Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor method is called for every object creation.

We can call parent's constructor method using parent::__construct() from the child constructor.

PHP also supports destructor like C++. This method is called as soon as the references of the object are removed or if we destroy the object . This feature has been included in PHP 5. Like constructor method we can call the destructor method of parent class by parent::__destruct().

The destructor is being called any how, means even after executing the exit() code destructor method could be called.

 

PHP Constructor & Destructor Example:

<?php

class ParentClass{

function __construct(){

print "In parent class <br/>";}}

class ChildClass extends ParentClass{

function __construct(){

parent::__construct();

print "In child class";}}

$obj1=new ParentClass(12);

$obj2=new ChildClass();

?>

Output:

In parent class
In parent class
IIn child class

 

Example:

<?php

class ParentClass{

function __construct(){

print "In parent class <br/>";

}

function __destruct(){

print "Parent Class Destructor called<br/>";

}

}

class ChildClass extends ParentClass{

function __construct(){

parent::__construct();

print "In child class<br/>";

}

function __destruct(){

print "Child Class Destructor called<br/>";

}

}

$obj1=new ParentClass();

$obj2=new ChildClass();

?>

 

Output:

In parent class
In parent class
In child class
Child Class Destructor called
Parent Class Destructor called

 

Advertisement

Related Tags for PHP Constructor and Destructor:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 18, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com