PHP MySQL tutorial

Parameterized Constructors in PHP

A constructor is the method of the class which is when called returns the object of the class. When you create a an object of the class using new followed by the class name and opening and closing parenthesis, you are basically calling default constructor of the class. In PHP, you can also pass parameter to the constructor. Such a constructor is called parameterized constructor.

Parameterized Constructor

Parameterized constructor is a constructor that accepts parameter and is normally used to initialize member variables at the time of object creation. It is similar to any function that accepts parameters. The parameterized constructor is created via __construct() function. Have a look at the following example to see how parameterized constructors can be used to initialize member variables at object creating time.

itemname = $name;
           $this->itemprice = $price;   
       /* Function to get name of item */
      function getName(){
         echo $this->itemname ."
"; } } // Creating objects of Item class. $item1 = new Item("Laptop", 35000); $item2 = new Item("LCD", 10000); $item1 -> getName(); $item1 -> getPrice(); $item2 -> getName(); $item2 -> getPrice(); ?>

Download the code
Run the code

In the above code the Item class is defined. It has a parameterized constructor which takes two parameters which are used to initialize the itemname and itemprice member variables of the Item class. Now, if you look at the object creation, you will see that after new and the class name, two values are being passed in the parenthesis. This is basically a call to parameterized constructor which will initialize two member variables with the values and then return the object. Now, if you call the getName and getPrice functions on the objects, you will see those values displayed in the output since the member variables have already been initialized via constructor.

<<< Introduction to Object Oriented Programming in PHPInheritance in Object Oriented PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .