PHP MySQL tutorial

Introduction to Object Oriented Programming in PHP

Object oriented programming is a programming architecture where real world entities are represented in the form of objects in a program. Traditional programming languages such as C++, C# and JAVA are implementing OOP principles for years. However, OOP is new to PHP. This article presents a very brief introduction to object oriented programming in PHP.


A class is a blue print which serves as foundation for building objects. Class defines how the object will look like, what members it will contain and what functionalities it will perform. Class itself is nothing, class once created cannot do anything itself except serving as a map for objects.


Object is actual representation of a class. The characteristics of a class are physically implemented via an object. Using object you can access member variables, retrieve or store values in those values and perform functionalities by calling class functions. Let’s have a look at a simple example that demonstrates how class is defined and how its objects can be created.

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

Download the code
Run the code

Defining a Class

In the above code a class named Item has been defined. Class is defined using class keyword followed by the name of class. The body of the class is enclosed in curly braces. The Item class contains two member variables itemname and itemprice. The class also contains four functions: two to set and get the name of the item and the remaining two to set and get the price of the item. Have a look at the setprice and setname functions. These functions take one parameter and store that value in the member variable. To access member variable within a class the keyword $this is used followed by -> and the member variable name except the $ sign.

Creating an Object

To create an object of the class, the keyword new is used followed by the name of the class and opening and closing bracket. This is basically a call to the default class constructor. Now to access member variables or functions of a class, the name of the object is used followed by single array and the function to be called.

<<< Validation and Sanitizing Data Via PHP FiltersParameterized Constructors in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .