Home > PHP, PHP Tutorials, PHP5 OOPS Tutorials > PHP5 Tutorial – Creating a PHP5 Constructor __construct()

PHP5 Tutorial – Creating a PHP5 Constructor __construct()

November 14th, 2007 admin Leave a comment Go to comments

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

Categories: PHP, PHP Tutorials, PHP5 OOPS Tutorials Tags:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. hi
    June 11th, 2008 at 13:20 | #1

    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.

  2. vimal
    November 4th, 2008 at 17:16 | #2

    very useful…thanx

  3. Amit
    April 15th, 2009 at 21:05 | #3

    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.

  4. admin
    April 16th, 2009 at 10:02 | #4

    Hi Amit,

    Thank you for this observation. I have fixed it.

    Thanks again :)

    Regards,
    Suniil

  5. manmca
    May 20th, 2009 at 15:29 | #5

    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

  6. admin
    May 22nd, 2009 at 08:28 | #6

    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

  7. May 22nd, 2009 at 09:35 | #7

    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…

  8. admin
    May 26th, 2009 at 19:20 | #8

    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

  9. sombir Jangra
    June 26th, 2009 at 12:28 | #9

    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

  1. No trackbacks yet.
Enter this code to leave comment (Sorry, but bots get me crazy :) )