PHP Constructors and Destructors

Constructors : PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

__construct
<?php

class TestClass {
function __construct() {
print “Constructor Initialized”;
}
}

$obj = new TestClass();

?>

OUTPUT :
Constructor Initialized

Destructors : PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

__destruct
<?php

class MyTestClass {
function __construct() {
print “In constructor< br/ >”;
$this->name = “MyDestructableClass”;
}

function __destruct() {
print “Destroying ” . $this->name;
}
}

$obj = new MyTestClass();

?>

OUTPUT :
In constructor
Destroying MyDestructableClass

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


www.phpprogram.net