Monday, November 26, 2012

Constructors and Destructors

Constructor

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.

Syntax:
void __construct ([ mixed $args [, $... ]] )

For example:

<?php
class constExample{
    function __construct()
    {
        echo "This will execute without calling a method";
    }

   
}

$obj = new constExample();

?>

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.

Syntax:
void __destruct ( void )

For example:
<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

No comments:

Post a Comment