Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

The idea of constructor is to prepare initial bunch of data for the object, so it can behave expectedly.

Just call a method is not a deal, because you can forget to do that, and this cannot be specified as "required before work" in syntax - so you'll get "broken" object.

Constructors are good for a variety of things. They initialize variables in your class. Say you are creating a BankAccount class. $b = new BankAccount(60); has a constructor that gives the bank account an initial value. They set variables within the class basically or they can also initialize other classes (inheritance).

The constructor is for initialisation done when an object is created.

You would not want to call an arbitrary method on a newly created object because this goes against the idea of encapsulation, and would require code using this object to have inherent knowledge of its inner workings (and requires more effort).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top