Showing posts with label Desctructor. Show all posts
Showing posts with label Desctructor. Show all posts
Constructor and Desctructor.
Posted by Raj
Constructor:
PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object.
function __construct() {
//
}
Example:
<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
}
class ChildClass extends MainClass {
function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}
$obj = new MainClass();
$obj = new SubClass();
?>
Note: If PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class.
Destructor:
The destructor method will be called as soon as Classes destroy the object.
function __destruct() {
//
}
Example:
<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
function __destruct() {
print "Destroying \n";
}
}
class ChildClass extends MainClass {
function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}
$obj = new MainClass();
$obj = new SubClass();
?>
Note:The destructor method will be called even if script execution is stopped using exit().
PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object.
function __construct() {
//
}
Example:
<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
}
class ChildClass extends MainClass {
function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}
$obj = new MainClass();
$obj = new SubClass();
?>
Note: If PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class.
Destructor:
The destructor method will be called as soon as Classes destroy the object.
function __destruct() {
//
}
Example:
<?php
class MainClass {
function __construct() {
echo "In MainClass constructor\n";
}
function __destruct() {
print "Destroying \n";
}
}
class ChildClass extends MainClass {
function __construct() {
parent::__construct();
echo "In SubClass constructor\n";
}
}
$obj = new MainClass();
$obj = new SubClass();
?>
Note:The destructor method will be called even if script execution is stopped using exit().