OOPS in PHP 5 - __construct() Method
Constructor in OOP Language are special function that gets fired whenever object of a class is instantiated. This is useful for initializing class data members before calling the class methods. PHP5 uses special keyword “__construct” to define constructor of the class.
Example 1:
< ? class employee { function __construct() { echo "Constructor Called"; } } $a = new employee(); $a = new employee; ?>
Explanation:
Here i initializing the employee class which internally calls its constructor.
Example 2:
< ? class employee { function __construct() { echo "Constructor Called"; } } $a = new employee(12); ?>
Explanation:
Now here we are passing a value to the constructor but the constructor definition does not have a argument definition. In OOP language like Java, C++, .Net this will throw an error but in PHP5 this will works as PHP5 implements loosely typed techniques and does not fully support Function OverLoading Technique.
To provide backward compatibility with PHP4, PHP5 engine first checks if the class provides a __construct() method, if not it looks for a method as the same name of the class (as per PHP4)
NOTE:
To create an instance of a class, the constructor should be define as public.
Similar Posts
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


Wonderful write up discussing PHP5 - __construct() Method | Techie Zone! I love your articles.