PHP Constructor and Destructor


 

PHP Constructor and Destructor

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.

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/>";

}

0

}

class ChildClass extends ParentClass{

function __construct(){

1

parent::__construct();

print "In child class<br/>";

}

2

function __destruct(){

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

}

3

}

$obj1=new ParentClass();

$obj2=new ChildClass();

4

?>

 

Output:

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

 

Ads