__construct in PHP 5


A constructor in PHP is a method that gets called when a new object of a class is instantiated.

In certain situations, classes may need some or all of its attributes to be defined when the object is instantiated. For example, a class may need to create a database connection before it can make use of its methods therefore the database connection details (which are stored in class attributes) need to be defined when the object is made.


Using a constructor is easy, its done using a pre-defined method name:

Look at the example class below:

Now when you instantiate the web developer class object you must parse oneparameter to the class otherwise PHP will throw an error:

You can now access the properties of the ‘WebDeveloper’ object: