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().
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
constructor,
Desctructor,
OOP interview questions and answers,
PHP,
PHP interview questions and answers
.You can leave a response, or trackback from your own site.