PHP - Adding Constructors to class


PHP provides you with two special methods to create and delete objects.

An object's constructor method is called after the object is created.

The destructor method is called just before the object is freed from memory.

To create a constructor, simply add a method with the special name __construct() to your class.

PHP looks for this special method name when the object is created; if it finds it, it calls the method.


         class MyClass {
           function __construct() {
             echo "I've come into being. \n";
           }/*from  ww  w.j a  v  a2 s  . c  o  m*/

         $obj = new MyClass;  


Here, MyClass, contains a very simple constructor that displays the message.

When the code then creates an object from that class, the constructor is called and the message is displayed.

You can pass arguments to constructors.


         class Person {
           private $_firstName;
           private $_lastName;
           private $_age;

           public function __construct($firstName, $lastName, $age) {
             $this->_firstName = $firstName;
             $this->_lastName = $lastName;
             $this->_age = $age;/* ww w .  j  a  v  a  2  s .  c  om*/

           public function showDetails() {
             echo "$this->_firstName $this->_lastName, age $this->_age \n";

         $p = new Person("James","Sim", 28);


The Person class contains three private properties and a constructor that accepts three values, setting the three properties to those values.

It contains a showDetails() method that displays the property values.

The code creates a new Person object, passing in the initial values for the three properties.

These arguments get passed directly to the __construct() method, which then sets the property values accordingly.

The last line then displays the property values by calling the showDetails() method.

If a class contains a constructor, it is only called if objects are created specifically from that class.

If an object is created from a child class, only the child class's constructor is called.

If necessary you can make a child class call its parent's constructor with parent::__construct().

Related Topic