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
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
No comments:
Post a Comment