Featured Posts

Writing Website Scrapers in PHPWriting Website Scrapers in PHP This article discusses about how to write a website scraper using PHP for web site data extraction. The concepts taught can be applied and programmed in Java, C#, etc. Basically any language that has a...

Readmore

12 common programming mistakes to avoid12 common programming mistakes to avoid Programming is an art and science and like all art and science the only way to learn is from mistakes. I have made many... and I would like to share with you the mistakes that I have made over my journey...

Readmore

7 habits of highly effective freelance programmers7 habits of highly effective freelance programmers I have developed these based on my freelancing experience. Though I have discontinued freelancing, but would like to share my practices with you. These are basic practices and have been developed over...

Readmore

  • Prev
  • Next

PHP5 Tutorial - Creating a PHP5 Constructor __construct()

Posted on : 14-11-2007 | By : admin | In : PHP, PHP Tutorials, PHP5 OOPS Tutorials

9

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.

What does this all mean?
Lets revisit that definition in more simple terms. 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.




Why do we need a Constructor?
It is needed as it provides an opportunity for doing necessary setup operations like initializing class variables, opening database connections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used.

PHP5 Constructor
In PHP5 a constructor is defined by implementing the __construct() method. This naming style has been introduced in PHP5. In PHP4, the name of the constructor was the same name as that of the class. So, for example if you had a class Customer, you would have to implement a function Customer().

PHP5 to be backward complaint also supports the PHP4 rule. When an object is created, PHP5 searches for __construct() first. If __construct() is not defined it then searches for a method with the same that of the class. However, if you define both; PHP5 will first search for __construct() method and execute it if available, otherwise it will execute the same class name function.

Let’s look at how to define a PHP5 Constructor

class Customer { 
	public function __construct() {
		//code
	}
}

Let’s look at a real example:

class Customer { 
	private $first_name;
	private $last_name;
	private $outstanding_amount;
 
	public function __construct() {
		$first_name = "";
		$last_name = "";
		$outstanding_amount = 0;
	}
 
	public function setData($first_name, $last_name, $outstanding_amount) {
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->outstanding_amount = $outstanding_amount;
	}
 
	public function printData() {
		echo "Name : " . $first_name . " " . $this->last_name . "\n";
		echo "Outstanding Amount : " . $this->outstanding_amount . "\n";
	}
 
}
 
$c1 = new Customer();
$c1->setData("Sunil","Bhatia",0);

In the above example on line number 26, we create a new object of the Customer class. the ‘new’ operator is responsible for creating the Customer class. At this point PHP5 searches the Customer class to see if a constructor has been defined. Therefore, it calls the constructor method i.e. __construct() defined starting from line no 7. The __construct() method sets the $first_name and $last_name to blank and sets the $outstanding_amount to zero.

Parameterized Constructor or Argument Constructor

A parameterized or argument constructor is a constructor which accepts values in the form of arguments in the constructor. Unlike other programming languages where overloaded argument constructors is possible, in PHP5 you cannot overload constructors.

Example:

class Customer { 
	private $first_name;
	private $last_name;
	private $outstanding_amount;
 
	public function __construct($first_name, $last_name, $outstanding_amount) {
		$this->setData($first_name, $last_name, $outstanding_amount);	
	}
 
	public function setData($first_name, $last_name, $outstanding_amount) {
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->outstanding_amount = $outstanding_amount;
	}
 
	public function printData() {
		echo "Name : " . $first_name . " " . $this->last_name . "\n";
		echo "Outstanding Amount : " . $this->outstanding_amount . "\n";
	}
 
}
 
$c1 = new Customer("Sunil","Bhatia",0);

In the above example on line number 24, we create a new object $c1 and pass values “Sunil”, “Bhatia” and zero to the constructor defined on line number starting 7. The constructor now takes 3 arguments and stores them in the internal private variable $first_name, $last_name and $outstanding_amount respectively.

In the next tutorial you will learn about PHP5 Destructor.

Feel free to write comments if you need more examples or if you need to ask a question on PHP5 Class. You can also subscribe to my notification service to be informed as an when a new tutorial article goes online. Subscribe Below




Related Posts on PHP5 Tutorial - Object Oriented Programming (OOPS)

  1. PHP5 Tutorial - Learn to create a PHP5 Class
  2. PHP5 Tutorial - Learn to Create a PHP5 Class Object
  3. PHP5 Tutorial - Defining Attributes of a PHP5 Class
  4. PHP5 Tutorial - Defining Methods of a PHP5 Class
  5. PHP5 Tutorial - Creating a PHP5 Constructor __construct()
  6. PHP5 Tutorial OOPS - Creating a PHP5 Destructor __destruct()
  7. PHP5 Tutorial OOPS - PHP5 Class Access Specifiers - public, private and protected
  8. PHP5 Tutorial - Magic Methods - __toString() method
  9. PHP5 Tutorial - Magic Methods - __get() and __set()
  10. PHP5 Tutorial - Magic Methods - __isset() and __unset()
  11. PHP5 Tutorial - Magic Methods - __call() method
  12. PHP5 Tutorial - Magic Methods - __autoload() method
  13. PHP5 Tutorial - Magic Methods - __sleep() and __wakeup()
  14. PHP5 Tutorial - Magic Methods - __clone() method

Your email:

 

Comments (9)

the lines:

echo “Name : ” . $first_name . ” ” . $last_name . “\n”;
echo “Outstanding Amount : ” . $outstanding_amount . “\n”;

Should be”

echo “Name : ” . $this->first_name . ” ” . $this->last_name . “\n”;
echo “Outstanding Amount : ” . $this->outstanding_amount . “\n”;

Regards.

very useful…thanx

Hello,

The following line of code will be modified.
public function printData() {
echo “Name : ” . $first_name . ” ” . $last_name . “\n”;
echo “Outstanding Amount : ” . $outstanding_amount . “\n”;
}

Modified code is as below.
public function printData() {
echo “Name : ” . $this->first_name . ” ” . $this->last_name . “\n”;
echo “Outstanding Amount : ” . $this->outstanding_amount . “\n”;
}

Please check and let me confirm about it.

Regards.

Hi Amit,

Thank you for this observation. I have fixed it.

Thanks again :)

Regards,
Suniil

I think u cant set class variable directly like this…. (in your first example)

public function __construct() {
$first_name = “”;
$last_name = “”;
$outstanding_amount = 0;
}

you have to use $this to access class variables.

what u say?
manmca

Hi Manmca,

In PHP you will need the $this variable inside any class function.

Unlike C++ or Java where accessing member variables without ‘this’ variable is allowed.

For all people with experience in C++, Java & .NET - this is a big deal to learn - as the language is structured that way.

Read more about $this variable here:
http://www.sunilb.com/php/php-tutorials/php5-tutorial-this-variable-explained

Regards,
Suniil

well sunil, constructor is also a method and if u dont use this under constructor u cant set variables value…

class Customer {
private $first_name;
private $last_name;
private $outstanding_amount;

public function __construct() {
$first_name = “sunil”;
$last_name = “bhatiya”;
$outstanding_amount = 0;
}

public function setData($first_name, $last_name, $outstanding_amount) {
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->outstanding_amount = $outstanding_amount;
}

public function printData() {
echo “Name : ” . $this->first_name . ” ” . $this->last_name . “\n”;
echo “Outstanding Amount : ” . $this->outstanding_amount . “\n”;
}

}

$c1 = new Customer();
$c1->printData();

here u cant getting $firstname and $lastname, while u trying to set it from consturctor.. instead if u used …

public function __construct() {
$this->first_name = “sunil”;
$this->last_name = “bhatiya”;
$this->outstanding_amount = 0;
}

then results will print ur firstname, lastname and outstanding amount which u set from constructor…

have tested it with php 5 :)
what u say?
manmca…

Hi Manmca,

Yes, you are right. A constructor is also a method and hence if you don’t use the $this variable along with variable names to assign something, it creates a new variable and stores the value in the newly created variable.

However, if you use the $this variable, the class member variables are modified.

Regards,
Suniil

I think u can’t set class variable directly like this…. (in your first example)

public function __construct() {
$first_name = “”;
$last_name = “”;
$outstanding_amount = 0;
}

you have to use $this to access class variables.
for example:
public function __construct() {
$this->$first_name = “”;
$this->$last_name = “”;
$this->$outstanding_amount = 0;
}

what u say?
Please check and let me confirm about it.
sombir jangra

Write a comment

Enter this code