views:

626

answers:

2

Hi Guys,

In my quest in trying to learn more about OOP in PHP. I have come across the constructor function a good few times and simply can't ignore it anymore. In my understanding, the constructor is called upon the moment I create an object, is this correct?

But why would I need to create this constructor if I can use "normal" functions or methods as their called?

cheers, Keith

+7  A: 

Yes the constructor is called when the object is created.

A small example of the usefulness of a constructor is this

class Bar
{
    // The variable we will be using within our class
    var $val;

    // This function is called when someone does $foo = new Bar();
    // But this constructor has also an $var within its definition,
    // So you have to do $foo = new Bar("some data")
    function __construct($var)
    {
        // Assign's the $var from the constructor to the $val variable 
        // we defined above
        $this->val = $var
    }
}

$foo = new Bar("baz");

echo $foo->val // baz

// You can also do this to see everything defined within the class
print_r($foo);

UPDATE: A question also asked why this should be used, a real life example is a database class, where you call the object with the username and password and table to connect to, which the constructor would connect to. Then you have the functions to do all the work within that database.

Ólafur Waage
Thanks for the reply Ólafur. If possible, could you comment each line for me to better understand?K
Keith Donegan
+21  A: 

The constructor allows you to ensure that the object is put in a particular state before you attempt to use it. For example, if your object has certain properties that are required for it to be used, you could initialize them in the constructor. Also, constructors allow a efficient way to initialize objects.

Brian Fisher
Thanks Brian, perfect explanation!
Keith Donegan
+1 for mentioning state
Andrew Hare