Definition of a Constructor

A constructor is a special function of a class that is automatically executed whenever an object of a class gets instantiated.

A constructor is a special function – this means that a constructor is a function; but its special. But, why is it special? It’s special because it is automatically executed or called when an object of a class is created.

PHP5 will first search for __construct() method and execute it if available, otherwise it will execute the same class name function.

Example:
Code:

class  Student {
	var $first_name;
	var $last_name;
	
 
	public function __construct() {
		 echo $first_name = "Tom"."
"; echo $last_name = "Cruise"."
"; } public function setData($first_name, $last_name) { $this->first_name = $first_name; $this->last_name = $last_name; } public function getData() { echo $this->first_name."
"; echo $this->last_name; } } $c1 = new Student(); $c1->setData("John","Abraham"); $c1->getData();

Output:

Tom
Cruise
John
Abraham

Explanation:

In the above example , we create a new object of the Student class. the ‘new’ operator is responsible for creating the Student class. At this point PHP5 searches the Student class to see if a constructor has been defined. Therefore, it calls the constructor method i.e. __construct(). The __construct() method sets the $first_name and $last_name to Tom and Cruise.

eXTReMe Tracker