__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: 

<?php
  public function __construct() { 
    // code here
  }
?>

 Look at the example class below: 

<?php
  class WebDeveloper {
    public $name;
    public function __construct($name) {
      $this->name = $name
    }
  }
?>

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

<?php
  $developer = new WebDeveloper('jordizle');
?>

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

<?php
  echo $developer->name;
?>

Your comments.