CONSTRUCTOR and DesTruCtoR in php


As a developer “Constructor” is very common to us and we use it very frequently. But do we know what is destructor and when to use it?

Yes the names describe their meanings themselves. Constructor and destructor are 2 methods of a class which are called at the time of object construction and destruction respectively.

Constructor:

How to create:

Generally the way of creating a constructor is creating a method, name of which is same as class name.

For Example:

class foo {
    function foo()
    {
        // PHP 4 style constructor
    }
}

Whereas PHP5 introduce a new magic method “__construct()” to declare a constructor.

The benefit of this method is if sometime we need to change the name of class, we don’t need to change the name of constructor.

For Example:

class newFoo {
    function __construct()
    {
        // PHP 5+ style constructor
    }
}

PHP5 first searches for magic method style constructor. If not present, it searches for a method, same name with class name. So, both style works.

Why to use:

Constructors are useful for initializing an object’s properties, or for performing startup procedures. For example, need to connect to database or set some specific set of configuration or fetch some remote file and cache it for quick usage.

Destructor:

How to create:

PHP 5 introduces a destructor concept similar to OOP concept. Magic method “__destruct()” is used to declare a destructor.

For Example:

class foo {
    function __construct()
    {
        echo ‘Constructor called’. PHP_EOL;
    }
    function __destruct()
    {
        echo ‘Destructor called’;
    }
}
new foo();

This code will display:

Constructor called
Destructor called

REMEMBER that destructor will not be called till the last reference of the object is gone, and this may not take place when you want or expect it.

For Example:

$obj1 = new foo();
$obj2 = $obj1;
unset($obj1);

This one will not call destructor as even if $obj1 is getting unset, another reference is still present.

Why to use:

Its mainly useful for performing cleanup procedures, such as disconnect remote connection, remove temporary files etc.

Hope this will help to effectively use constructor and destructor. 🙂

 

References:
http://php.net/manual/en/language.oop5.decon.php
http://www-numi.fnal.gov

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s