Classes and Objects are key part of object oriented programming (oop) in php. If you are directly here then I am assuming that you have basic knowledge of OOP. If you are beginner for oop and do not have good confidence on basics of classed and objects then please first go to Basics of OOP.

Who can Read this tutorial and what you can can learn here ?

This tutorial is for beginner who has some basic knowledge of oop. If you know what is oop, what is object and classes and what to learn its  implementation, then you are at right place. Before going further you should have basic understanding of oop, classes and object. Technical knowledge of oop is not commendatory for this tutorial.

This tutorial, we will start from the basic concept of classes and objects. Here we will start from how to create classes in php. How to create object of any class. And in later part we will explore some advance concept of object and class here. In short if you have basic knowledge of oop and want to learn classes and objects implantation in php then you are at right place.

Class In PHP

Concept of class ( or basic object oriented structure) introduced from php4. But complete coverage of class like access modifier or interface is introduced from php5. Creating class is very easy in php. You can create class with help of using class keyword in php. Following is a basic class example
class myOwnClass
{
//variables of the class
var $variable1;
var $variable2;
//Function of class
function mergeVariable()
{
return $this->variable1 . $this->variable2;
}
}

Class myOwnClass is created by using keyword class. Your name of the class will be general string without space. Also complete block of the class in enclosed within {}(see bold  braces). All variables of this class is defined in the beginning of the class. Variables are starting with var keyword. From php5 you can declare variable using its level of visibility also. For example if you want to declare $varaible1 to be accessible from anywhere then you can use public $variable1 instead of var $variable1. If you will use var $variable1 in php5, the variable will be treated as public by default.

Next part is function declaration of your class. As per the above example you can directly declare function as function mergeVariable(). It is very basic creation of function within your class and supports from php4. In php5 you can apply visibility on your function also. For the same function you can write in php5 like public function mergeVariable(). If you will not define your visibility factor by default your function will be treated as public.

following is example of same above class in php5:
class myOwnClass
{
//variables of the class
public $variable1;
private $variable2;
//Function of class
public function mergeVariable()
{
return $this->variable1 . $this->variable2;
}
}

So in the basic architecture of php4 and php5 class is almost same except use of visibility. We will visibility in depth in chapter Visibility in OOP. For now you just think that visibility is access factor of your class's method and variable. If you want your object to allow access of your variable or function then make it public. If you do not want your object to access methods and properties then make it private.

You can directly pass value to your class from by the class function parameter also. Function of the class always work like general function in the php. For example
{
//variables of the class
public $variable1;
private $variable2;
//Function of class
public function mergeVariable($third_var)
{
return $this->variable1 . $this->variable2. $third_var;
}
}

You can not create class with name stdClass in PHP. It is reserved class of the php. stdClass represent standard object. It is used to create empty object. You can use it without creating it. IF you will forcefully try to create class with name stdClass. PHP will throw fatal error with following message.
Fatal error: Cannot redeclare class stdClass

It is recommended to not create your function of the class starting with __ like __call. Because function started with __ is seems like magic function in php.

You can not breakup your class in several file. But withing your class function you can breakup it into multiple file. Let us understand this by example. Following is not allowed in your class
class myClass
{
public $abc;
public function test()
{
return $this->abc;
}
include "abc.php";
}

But following is allowed:
class myClass
{
public $abc;
public function test()
{
include "abc.php";
}
}

So while creating class you should take care of above practices.

Object IN PHP

Classes are useless without objects.  Object is an instance of your class.If you have class then you need to create object of the class to solve your problem using class. You can create object of your class by using new keyword.
$objClass = new myClass();
Now in above code you are creating object of class myClass in variable $objClass. You can create multiple object of your same class. Every object is different from other.
$objClass1 = new myClass();
$objClass2 = new myClass();

To completely understand object Let us create full class and their object. Here I will create class for interest calculation and then I will create object of that class and calculate interest.

//Creating class interestCalculator
class interestCalculator
{
public $rate;
public $duration;
public $capital;
public function calculateInterest()
{
return ($this->rate*$this->duration*$this->capital)/100;
}
}
//Creating various object of class interestCalculator to calculate interest on various amount
$calculator1 = new InterestCalculator();
$calculator2 = new InterestCalculator();
$calculator1->rate = 3;
$calculator1->duration =2;
$calculator1->capital = 300;
$calculator2->rate = 3.2;
$calculator2->duration =3;
$calculator2->capital = 400;
$interest1 = $calculator1->calculateInterest();
$interest2 = $calculator2->calculateInterest();
echo "Your interest on capital $calculator1->capital with rate $calculator1->rate for duration $calculator1->duration is $interest1 <br/> ";
echo "Your interest on capital $calculator2->capital with rate $calculator2->rate for duration $calculator2->duration is $interest2 <br/> ";

Please run above code in browser. You will get following output.classes and objectsNow please analyse above code carefully. We have created two object of interestCalculator class in variable $calculator1 and $calculator2. Now property value of both objects are different. for example $calculator1 capital is 300 and $calculator2 capital is 400. Whenever you will call calculateInterest function of the both object then they will calculate interest on their own properties.

Now just analyse code of your class interestCalculator
class interestCalculator
{
public $rate;
public $duration;
public $capital;
public function calculateInterest()
{
return ($this->rate*$this->duration*$this->capital)/100;
}
}

You can find that class has 3 variable or properties ($rate , $duration, $capital). Now look into function calculateInterest. In the body of the function we have used variable $this. $this is system defined object variable of the class. $this is object of self class in the current context. For the both object of interestCalculator class $this object is different. When you have object $calculator1 then $this->rate is 3 and in case of $calculator2 $this->rate is 3.2
public function calculateInterest()
{
$rate = 5;
return ($this->rate*$this->duration*$this->capital)/100;
}
}

In above function  of class $this->rate and $rate is different. $this->rate will always has values assigned by the object of the class but $rate is fix value. If you will replace $this->rate to $rate your rate of interest will always be 5.
public function calculateInterest()
{
$rate = 5;
return ($this->rate*$this->duration*$this->capital)/100;
}
}

You can create object of the class in some different way also. Following is some of the example of creating object of class.
$className = 'interestCalculator';
$calc1 = new $className();

From php 5.3 onward you can create object of class
$cls1 = new interestCalculator();
$cls2 = new $cls1;

Constructor of Classes and Objects

Constructor is nothing but a function defined in your php class. Constructor function automatically called when you will create object of the class. As soon as you will write $object = new yourClass() your constructor function of the class will be executed. In php4 you can create constructor by creating function with same name of your class. But from php5 you can also create constructor by defining magic function __construct. Please go through the blow example of the constructor.

PHP 4 constructor(will work in php 5 also)
class interestCalculator
{
var $rate;
var $duration;
var $capital;
//Constructor of the class
function interestCalculator()
{
$this->rate = 3;
$this->duration = 4;
}
}

PHP5 constructor
class interestCalculator
{
public $rate;
public $duration;
public $capital;
//Constructor of the class
public function __construct()
{
$this->rate = 3;
$this->duration = 4;
}
}

In both whenever instance of the class will be created rate will be set to 3 and duration will be set to 4. But difference is in way of calling the constructor. In php4 you were limited to create constructor by creating function with same name of the class. But in php5 you can either create function with same name or create a function __construct to create constructor of the class. You can also pass parameter in the constructor.
class interestCalculator
{
public $rate;
public $duration;
public $capital;
//Constructor of the class
public function __construct($rate , $duration)
{
$this->rate = $rate;
$this->duration = $duration;
}
}
$objCls = new interestCalculator(3.2 , 7) //passing value of $rate and $duration

If you have created parameter in the constructor you need to pass value for them on the time of object creation. $objCls = new interestCalculator(3.2 , 7). If you will not send value php will throw error.

Playing with visibility and other feature of the constructor

Let us explore in depth of constructor for our classes and objects in php. All implantation is described here are considered only for php5.
Did you noticed that I have created my constructor function public. If not then please go to above section and explore. Reason behind creating constructor function public is it is accessible from outside of the class. This function is executed when we are creating object. So php will aways through error if you will create your constructor private. Let us try below code:
class interestCalculator
{
public $rate;
public $duration;
public $capital;
//Constructor of the class
private function __construct($rate , $duration)
{
$this->rate = $rate;
$this->duration = $duration;
}
}
$objCls = new interestCalculator(3.2 , 7); //passing value of $rate and $duration

It will give you following output

Fatal error: Call to private interestCalculator::__construct() from invalid context

As you can define your constructor by creating function with same name of class(event in php5), if you will use following code then your output will be same:
class interestCalculator
{
public $rate;
public $duration;
public $capital;
//Constructor of the class
private function interestCalculator($rate , $duration)
{
$this->rate = $rate;
$this->duration = $duration;
}
}
$objCls = new interestCalculator(3.2 , 7);

Following error you will receive

Fatal error: Call to private interestCalculator::interestCalculator() from invalid context

So in short you can not make your constructor private. If you will make your constructor private then you will receive an error.

Now Just think that you can define your constructor either by creating function with same name of the class or by crating function with name __construct. Now what happen if you will use both thing in your single class.  Let us try this code:
class test
{
public function __construct()
{
echo 1;
}
function test()
{
echo 2;
}
}
$t = new test();//Output will be 1

It will give you output 1. Means your __construct function is called. So if you have __construct then it will be the first preference. If __construct function is not present then it will search for the function with the same name of class. Think what happen in case if you have both option and your function __construct is private. Try this code
class test
{
private function __construct()
{
echo 1;
}
function test()
{
echo 2;
}
}
$t = new test();

You will get following error:

Fatal error: Call to private test::__construct() from invalid context

Best Practice of Classes and Objects

Following are some best practice of using classes and objects in your application.

  1. Instead of assigning variable of the classes after creating object it is good if you use constructor. 
  2. Use visibility as required. Do not make your variable and method either more secure or completely open. Over security will effect your flexibility, under security will distrust your structure.
  3. Follow some convention in your classes and objects. Like start all public method with camel case, all protected method and varaible prefix with _ etc. It will give you better visibility.
  4. Do not try to do every thing in single class. Create class very specific to your requirement. It will same your time and execution.
  5. Always try to create every class in separate file and follow some naming convention.

 

Download Code (Experimental) for Classes and Objects.

For further detail on Classes and Object in PHP you may read following:
http://www.php.net/manual/en/language.oop5.basic.php
http://php.net/manual/en/keyword.class.php

Next >> Magic Function in PHP  OOP

Tagged with:
 

24 Responses to Classes and Objects Tutorial in PHP

  1. Class names must be started in capital letters?

  2. No this is not required. You can name it as same as php guideline

  3. snehal says:

    can another class be created inside a class block?

  4. Richard Winters(of Band Of Brothers fame) says:

    @snehal-No u cannot have another class defined inside a class.However,u can make use of include or require to make use of other class elements.

  5. Rajesh A says:

    grate thanks to uuuuuuuuuuuuuuuu….sir…….this post very use full for me

  6. mmts says:

    Thank you so much for your step by step tutorial. It helps me a lot to understand oop.

  7. Jay says:

    Thanks to great description … Lot of think to clear …..

  8. Nice tutorial mate, Thanks a lot!!

  9. Kuldeep Shukla says:

    Thank you so much for your step by step tutorial.It’s very good.

  10. Mani says:

    Thanks for Step by Step Guide.

  11. amit bindal says:

    great tutorial!!!!

  12. thank you but what about inheritence in php5

  13. anilmcmt says:

    nice tutorial

  14. sam says:

    superrrrrrrr..nicee

  15. Arunstalin says:

    Best tutorial compare to others… thanks.. want to more MVC tutorials also

  16. rahul says:

    i like your way to describe

  17. Manoj says:

    best tutorial and described in a simple way..

  18. Dmitry says:

    Awesome tutorial, thanks Ankur.

  19. juhi says:

    nice tutorial…:)

  20. sohail says:

    this site is perfect i learn more use this site

  21. Mike says:

    Gah OOP is so hard to learn. Is it preferably just for larger projects?
    I have mainly worked with ASP before and as everyone knows, there is not a shred of OOP in ASP 3.0 …

  22. Thank you so much.. It is very helpful me ..

  23. thanku so much for this tutorial……….:)

Leave a Reply