__construct in PHP 5

-

Introduction

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.

Usage

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 one parameter to the class otherwise PHP will throw an error:

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

Comments

Visitor stats.