Object Oriented Programming Concepts in PHP

This article is very useful for beginners who want to take up their coding level to the next level using object oriented programming concepts in php. This post covers complete oops concepts like classes and objects, inheritance, abstraction, encapsulation, polymorphism, interface, abstract class, php access modifiers, constructor and destructor.

Inheritance, Aggregation, Composition, Encapsulation and Polymorphism these are known as fundamentals of Object Oriented Programming. Object Oriented concepts are based on these fundamentals.

Before object oriented came into existence developers were using fuctional programming means function based programming where to create function for every module.

Problems with functional programming

For small projects it was fine to follow the function-based programming approach but for large projects or applications it was difficult to follow functional programming. Some of problems are listed below that linked with functional programming.

Functions are is not resusable.

No proper naming conventions while creating functions.

For new functionality or any minimal change in the application we need to use new function. So for every change or addition in the application we have to create a new function.

It was difficult to remember all those function names.

We cannot modify or extend the existing function in the project.

There is no provision to encapsulate/hide certain important function names from outside the world (Means - User-Interface Screen).

There is no provision to display only certain important function names to outside the world (Means - User-Interface Screen).

Benefits of using object oriented programming in PHP Applications

Using the classes we can templatized our code in proper section because of this changes made in class will not effect any other part of the program.

Complete project becomes easy to understand and maintain even after the years.

Easy to maintain large projects.

Extending of the project becomes easy. OOPs gives us flexibility to extend the project using inheritance concept.

Code is maintained proper with proper security using encapsulation concept.

Data Hiding using encapsulation helps the programmers to build a secure program.

Using inheritance programmers can extend any part of code without affecting any other part of program.

Software complexity can be easily managed using encapsulation and abstraction.

With PHP 5, the object model was rewritten for better performance and more features.

PHP 5 object model comes with more added features like magic methods, interfaces, property visibility, abstract classes, cloning and typehinting.

PHP 5 made object model more powerful and efficient for php developers to organize their code more logically and easy to understand.

PHP Classes and Objects with an Example

Class Definition: A Class is just a blue print or template or general thing. Class in php defined with "class" keyword followed by class-name then curly braces. curly braces are scope of a class to write class code as shown in below snippet of code.

 
<?php

class clsSendSMS{
	   
	   public $from;
	   public $provider;
	   public $message;
	   public $mobilenumber;
	   
	   public function PrintSMS(){
		      
		echo $this->from." ".$this->provider." ".$this->message." ".$this->mobilenumber;      
	   }
	   
}

?>

As you see above code that we have created a php class "clsSendSMS" with properties and a single method "PrintSMS()".

Object Definition : An Object is an instance of the class. An object is a software bundle of related properties and related methods in a class.These objects are specialization of a class. An object is characterized by attribute (property), behavior (method) and Identity (Object's unique name). To access any method from the class we need an object of that class.

To create an object for a class we need to use "new" keyword followed by class-name and should be assigned it to the unique php variable.

For an object name we can choose any unique name by using that object we can able to access properties and methods from a class.

If you want to use class instance inside the class scope then you can use "$this" variable.

"$this" variable is actually an object of current instance of a class and it can be accessed only within the class.

 
    
<?php

class clsSendSMS{
	   
	   public $from;
	   public $provider;
	   public $message;
	   public $mobilenumber;
	   
	   public function PrintSMS(){
		      
		echo $this->from." ".$this->provider." ".$this->message." ".$this->mobilenumber;      
	   }
	   
}

$objSMS = new clsSendSMS();


?>

As you see from an above code that we created an object with object name "$objSMS" which is an instance of class "clsSendSMS()".

Demonstration of Calling Member Functions and Properties

 
    
<?php

class clsSendSMS{
	   
	   public $from;
	   public $provider;
	   public $message;
	   public $mobilenumber;
	   
	   public function PrintSMS(){
		      
		echo $this->from." ".$this->provider." ".$this->message." ".$this->mobilenumber;      
	   }
	   
}


$obj = new clsSendSMS();


$obj->from="Gurunatha Dogi";
$obj->provider="Onlinebuff Services";
$obj->message="Happy Coding...!Friends";
$obj->mobilenumber="0123456789";



$obj->PrintSMS();

//Output : 

//Gurunatha Dogi Onlinebuff Services Happy Coding...!Friends 0123456789

?>


Access modifiers in PHP

Access modifiers means handling the visibility of methods and properties within the class.The visibility can be managed by using following keywords private, public and protected.

Private : Methods and Properties declared as "private" are accessible only within the class and these methods and properties are completely hidden or not accessible outside of class scope.

Public : Methods and Properties declared as "public" are accessible anywhere within the class and as well as outside of the class scope.

Protected : Methods and Properties declared as "protected" are accessible within the class scope and within the child classes.

Demonstration of Access Modifiers

 
    
<?php

class clsSendSMSAccessibility{
	   	 
	   protected $from;
	   public $provider;
	   private $message;

	   private function PrintSMS(){
		      
		......
	   }

	   public function PrintSMS(){
		      
		......
	   }

	   protected function PrintSMS(){
		      
		......
	   }
	   
}

?>

Inheritance in PHP

Inheritance is one of the object oriented concept in php. Inheritance helps us to create a new class from the existing class and enables us to get advantage to reuse or to extend or to modify the behavior of a functions defined in existing class.

Once we apply inheritance methodology on existing class then that existing class becomes "parent-class" or "base class".

The class which inherits methods and properties from "parent-class" is known as "derived class" or "child-class".

The big advantage of using inheritance that it allows code reusability or code extensibility and offers clear model structure which become easy to manage and handle.

Keyword to declare inheritance in php is by using "extends" keyword.

 
<?php

class ParentClass{
//....class code
} 

class ChildClass extends ParentClass{

//....class code
}

?>

Example of Inheritance using PHP

 
<?php

class clsSendSMS{
	   
	   var $from = "Parent Class";
	   var $provider = "PHP Provider";
	   var $message = "Happy Coding..!";
	   var $mobilenumber = "0123456789";
	   
	   public function PrintSMS(){
		      
		echo $this->from." ".$this->provider." ".$this->message." ".$this->mobilenumber;      
	   }
	   
	   public function SendSMS(){
		      
		echo "Sending SMS :: clsSendSMS";      
	   }
	   
}

class clsSendTextSMS extends clsSendSMS{
	   
	  var $from = "Child Class";
	  
	  public function SendSMS(){
	   
	   echo "Sending SMS :: clsSendTextSMS";      
	   
	  }
}

?>

Output 1
 
<?php

$obj = new clsSendSMS();

$obj->PrintSMS();

echo "<br>";

$obj->SendSMS(); /// Parent Class

?>
Output 2
 
<?php
$obj = new clsSendTextSMS();


$obj->PrintSMS();

echo "<br>";

$obj->SendSMS(); // Child Class

?>

As you see from above code that we have extended class "clsSendSMS()" code in the new class "clsSendTextSMS()". So when we inherited class "clsSendSMS()" to class "clsSendTextSMS()" using "extends" keyword then child-class "clsSendTextSMS()" automatically gets access to methods and properties present in the parent-class.It means to the child-class we can add more new methods/properties or we can rewrite those existing methods/properties present in the parent-class.By using the child-class (derived class) object we can retrive methods/properties present in child-class and as well as methods/properties present in parent-class.So it is proved that parent-class is just a generalized class and child-class is more specialized class than parent-class. So in OOPS if you are looking to extend any class code or to reuse any class code with more functionality with proper structure which can be maintained easily and understandable then use PHP Inheritance. PHP Inheritance gives you that flexibility to extend the code and resue.

Abstraction and Encapsulation in PHP

Abstraction and Encapsulation are the fundamental concepts of object oriented model in PHP. We have used abstraction and encapsulation both topics together because they both compliment each other. For example : It is like a car which hides its engine inside and expose only necessary things to drive it. so same way abstraction and encapsulation works in the php object model.

Displaying only necessary things to the outside world is known as abstraction and hiding unnecessary things from outside world is known as encapsulation for example on Television remote we can see only necessary buttons (sound, ON/OFF, channels etc) and unnecessary things like remote chip or remote circuit is completely hidden from outside of world why because normal people cannot understand that complexity of remote and they can understand only simple buttons which is needed to handle a Television. So thats why to keep it simple and easy to understand engineers displayed only buttons on remote control rest complexity part is hidden inside the remote cover.

So displaying only essential features of an object and hiding un essential things is called as Abstraction and Encapsulation. In other words abstraction is thinking in terms of design way to increase efficiency and encapsulation is a process of hiding the complexity of the code. Encapsulation acts as a protective barrier to abstraction. We can achieve encapsulation in a program if we make functions and properties as "private".Encapsulation is the technique of making the fields in a class as "private" and providing visibility to only necessary fields using "public" modifier. Encapsulation is a process of hiding complex code using "private" keyword and displaying only necessary code using "public" keyword (Abstraction).

Displayed code is known using "public" modifier is known as Abstraction.

Hiding complex code using "private" modifier is known as Encapsulation.

PHP Abstraction and Encapsulation with an example

 
<?php

class clsSendSMS{
	   

	   private $username="usrguru";
	   private $password="pwdguru";
	   private $httpapi;
	
	  
	   
	   public function SendSMS($mobile, $text, $from){
		
		      $apilink = MakeSMSAPI($mobile, $text, $from);

		      $ch = curl_init();

		      // set url
		      curl_setopt($ch, CURLOPT_URL, $apilink);
	      
		      //return the transfer as a string
		      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	      
		      // $output contains the output string
		      $output = curl_exec($ch);

		      echo "SMS Sucessfully Sent To - ".$mobile;
		
	   }
	   
	   private function MakeSMSAPI($mobilenumber, $message, $from){
		 
		      $httpapi = "SMSAPI?username=".$username."&password=".$password."&type=SingleSMS&mobile=".$mobilenumber."&message=".$message."&from=".$from."";
		 
		      return $httpapi;
		      
	   }
	   
}



$obj = new clsSendSMS();
$obj->SendSMS('0123456789', 'PHP SMS Testing', '0123456789');


?>


As you see from above snippet of code that we have exposed only "SendSMS()" method and hidden "MakeSMSAPI()" method because to send sms we need only "SendSMS()" make http api is not needed it can kept as hidden from outside object world.

So when any developer (User interface developer who works at design level) consumes your class "clsSendSMS" then he/she will able to see only necessary method "SendSMS()" with three input values which is needed to Send SMS. "MakeSMSAPI()" method is not needed to be exposed it internally can make http api and pass it to "SendSMS()" method internally.

So hey friends as you see we have exposed only that method which is needed to Send SMS so that exposed part of code is called as Abstraction and hidden other method and other properties which is not needed to be exposed and but they can work internally within the class so that hidden part of code is called as Encapsulation.

Polymorphism in PHP

Poly means many and morph means form so Polymorphism means many forms. In simple words one name and many different forms or one name with multiple functionality. There are two types of polymorphism in object oriented programming Static Polymorphism and Dynamic Polymorphism but unfortunately PHP does not support static polymorphism.Dynamic Polymorphism means its an ability to redefine methods in derived class with same name and same signature or with a same name and different signature. Dynamic polymorphism is also called as Run Time Polymorphism. Run time Polymorphism also known as method overriding.When two or more methods in child classes with same name and same input values but different in implementation is called as Method overriding.

Note : PHP does not support compile time polymorphism or static poly morphism.

PHP Polymorphism Example

    
<?php

class clsSendDefaultSMS{
	   

	   private $defaultmessage = "This is default message from PHP Server";
	   
	   protected $httpapi = "SMSAPIsendsms";
	   
	   protected $apiname = "PHP Gateway";
	   
	   public function SendSMS($mobile){
		
             echo $this->defaultmessage." Message Sent To - ".$mobile." via ".$this->apiname.", link : ".$this->httpapi;
		
	   }
	   
	   
}

class clsSendAlertSMS extends clsSendDefaultSMS {
	   

	   private $defaultmessage = "This is alert message from PHP Server";
	   
	   public function SendSMS($mobile){
		
             echo $this->defaultmessage." Message Sent To - ".$mobile." via ".$this->apiname.", link : ".$this->httpapi;
		
	   }
	   
	   
}

class clsSendTextSMS extends clsSendDefaultSMS {
	   
      	   public function SendSMS($mobile,$text){
		
             echo $text." Message Sent To - ".$mobile." via ".$this->apiname.", link : ".$this->httpapi;
		
	   }  
	   
}


class clsSendMultipleSMS extends clsSendDefaultSMS {
	   
      	   public function SendSMS($mobile1,$mobile2,$text){
	   
             echo $text." Message Sent To - ".$mobile1." & ".$mobile2." via ".$this->apiname.", link : ".$this->httpapi;
		
	   }  
	   
}



$obj = new clsSendTextSMS();
$obj->SendSMS('0123456789','Happy Coding...!');


?>

PHP Constructors

In PHP, Constructors are responsible for creating objects. Constructor function of a class get invoked automatically when an object of a class is created. Constructors does not have any return type so constructors does not return anything. Constructors can take any number of input values. It just ensures that an object should go through proper initialization process. Constructors are used when we want to set any property in class when an object is created or before an object is used.

For example : Let's say there is a class "clsDataConnection" and if you want to specify type of data connection when an object (clsDataConnection) is created then you can use constructor in the class to set any property which ensures that object will go through proper initialization process.

The syntax of a constructor in PHP 5

 
<?php
void "__construct()";
?>

In PHP 5 constructor usually starts with two underscores then followed by construct keyword. It looks like magic functions because all PHP 5 magic methods starts with two underscores so its also called as magic function.

PHP Constructor Example

 
<?php

class clsDataConnection {
	   
	private $typeofconnection;
	
	public function __construct($type){
	   
	   $this->typeofconnection = $type;
	   
	}
	
	public function MakeConnection(){
	   
	   if($this->typeofconnection == "MYSQL"){
		      
		      echo "MYSQL is now connected";
		      
	   }elseif($this->typeofconnection == "SQL"){
		      
		      echo "SQL is now connected";
		      
	   }elseif($this->typeofconnection == "ORACLE"){
		      
		      echo "ORACLE is now connected";
		      
	   }else{
		      
		      echo "Connection Problem";
	   }
	   
	   
	}
}

$obj = new clsDataConnection("MYSQL");
$obj->MakeConnection(); ///Output : MYSQL is now connected


$obj = new clsDataConnection("ORACLE");
$obj->MakeConnection(); ///Output : ORACLE is now connected
?>

PHP Destructor

Destructors are responsible for destroying objects.Destructor function invokes automatically when an object is no-longer in use in the application. It automatically closes all the available resources of an object. It automatically cleans the object from the memory. Destructor function is also useful if you want to write some clean codes like closing data connection, unset some class properties, clearing memory, closing socket connections and so on. In terms of managing the memory resources it is better to destroy an object when no longer needed.

The syntax of a destructor in PHP 5

 
<?php
void "__destruct()";
?>

In PHP 5 destructor usually starts with two underscores then followed by destruct keyword. It looks like magic functions because all PHP 5 magic methods starts with two underscores so its also called as magic function.

PHP Destructor Example

 
<?php

class clsConnection {
	   
	private $typeofconnection;
	
	public function __construct($type){
	   
	   $this->typeofconnection = $type;
	   
	   echo " Constructor :: ";
	}
	
	public function CreateConnection(){
	   
	   if($this->typeofconnection == "MYSQL"){
		      
		      echo "Making MYSQL connection ";
		      
	   }elseif($this->typeofconnection == "SQL"){
		      
		      echo "Making SQL connection ";
		      
	   }elseif($this->typeofconnection == "ORACLE"){
		      
		      echo "Making ORACLE connection ";
		      
	   }else{
		      
		      echo "Connection Problem ";
	   }
	   
	   
	}
	
	
	
	public function __destruct(){
		
		echo "<br> Destructor :: Terminating ".$this->typeofconnection." Connection";
	}
}

$obj = new clsConnection("SQL");
$obj->CreateConnection();


?>

Interface in PHP

Interface declared with "interface" keyword in PHP. Interface looks like a class having only methods/functions but with no-implementation and an interface cannot have member variables. Interface does not provide any implementations it provides only signatures of functions. Interface forces the implemented class to provide all the implementations. It is like a contract enforces by an Interface to the implemented classes to provide all the implementation inorder to execute the project. In PHP programming you cannot create an object for an Interface.

Interfaces are very useful when building a large project where you want to divide the project in the development teams. As a project leader you just need to create an interface with proper signatures and need to ask your development team to implement that interface and provide all the implementations. The main advantage is that forcefully they need to provide all the implementations for the signatures without tampering or changing the function name. As a project lead it becomes easy for you to remeber the function names in the project.

Declaration of Interface

 

<?php

interface INames{

/// code goes here 


}

?>

An Interface normally starts with "interface" keyword followed by Interface-Name and then in the curly braces we can do the following codings.

Inorder to implement an interface to the class we need to use "implements" keyword as shown in below snippet of code.

 
<?php

class clsNames implements INames{

/// code goes here 


}

?>

As you see from above code that we have successfully implemented an interface "INames" to the class "clsNames" by using "implements" keyword.

PHP Interface Example

 
<?php

interface IEmployee{
	
	public function setEmployeeDetails($employeename, $employeeaddress);
	public function getEmployeeDetails();
	public function CalculateSalary($incentive);
}


class clsEmployee implements IEmployee {
	
	private $emplname;
	private $empladdress;
	private $basicsalary = 5000;
	private $calculatedvalue;
	
	public function setEmployeeDetails($name, $address){
		
		$this->emplname = $name;
		$this->empladdress = $address;
		
	}
	
	
	public function CalculateSalary($incentives){
		
		$this->calculatedvalue = $this->basicsalary + $incentives;
	}
	
	public function getEmployeeDetails(){
		
		echo "Employe Details :: ".$this->emplname." ".$this->empladdress." ".$this->calculatedvalue;
	}
	
	
}

$obj = new clsEmployee();

$obj->setEmployeeDetails('guru','Mumbai');
$obj->CalculateSalary(15000);

$obj->getEmployeeDetails();

?>

Abstract Class in PHP

Abstract class in PHP is defined using "abstract" keyword as shown in below code.

 
    
<?php

abstract class absClass{
 
 //code goes here

}

?>

Abstract class like an interface enforces the implemented or extended classes to provide implementation for abstract methods. In abstract class we can define member variables and abstract method and non abstract method.

Abstract Method : In PHP 5 An Abstract method usually starts with "abstract" keyword followed by function name as shown below. These abstract methods can only be defined in abstract class only without an implementations (with only signature).

 

<?php

abstract class absClass{

  public abstract function Method1(); 

}

?>

Non Abstract Method : In PHP 5 Non Abstract Method contains no "abstract" keyword and need to provide implementations otherwise it will throw an error.

Abstract Class Example in PHP

 
<?php

abstract class absEmployee{
	
	protected $emplname;
	protected $empladdress;
	protected $calculatedvalue;
	protected $classname;
	
	
	abstract public function setEmployeeDetails($employeename, $employeeaddress);
	
	public function getEmployeeDetails(){
		
	  echo "Employe Details ".$this->classname." :: ".$this->emplname." ".$this->empladdress." ".$this->calculatedvalue;
		
	}
	abstract public function CalculateSalary($incentive);
}


class clsWorker extends absEmployee {

	private $basicsalary = 5000;
	
	public function setEmployeeDetails($name, $address){
		
		$this->emplname = $name;
		$this->empladdress = $address;
		$this->classname="clsWorker";
		
		
	}
	
	public function CalculateSalary($incentives){
		
		$this->calculatedvalue = $this->basicsalary + $incentives;
	}

}

class clsManager extends absEmployee {

	private $basicsalary = 10000;

	
	public function setEmployeeDetails($name, $address){
		
		$this->emplname = $name;
		$this->empladdress = $address;
		$this->classname="clsManager";
		
		
	}
	
	public function CalculateSalary($incentives){
		
		$this->calculatedvalue = $this->basicsalary + $incentives;
	}

}


class clsSeniorOfficers extends absEmployee {

	private $basicsalary = 9000;

	
	public function setEmployeeDetails($name, $address){
		
		$this->emplname = $name;
		$this->empladdress = $address;
		$this->classname="clsSeniorOfficers";
		
		
	}
	
	public function CalculateSalary($incentives){
		
		$this->calculatedvalue = $this->basicsalary + $incentives;
	}
	

}

class clsRetired extends absEmployee {

	private $basicsalary = 2000;

	
	public function setEmployeeDetails($name, $address){
		
		$this->emplname = $name;
		$this->empladdress = $address;
		$this->classname="clsRetired";
		
		
	}
	
	public function CalculateSalary($incentives){
		
		$this->calculatedvalue = $this->basicsalary + $incentives;
	}

}


$obj = new clsSeniorOfficers();

$obj->setEmployeeDetails('guru','Mumbai');
$obj->CalculateSalary(51000);

$obj->getEmployeeDetails();

?>

Difference between Interface and Abstract Class in PHP

Interface : It provides only signature of a function with no implementation

Abstract Class: It provides signature of a function and as well as implementation of a function.

Interface : We cannot do any implementations.

Abstract Class : Partial Implementation is possible using non abstract method.

Interface : In PHP 5 to implement an "interface" to a class we need to use "implements" keyword.

Abstract Class : In PHP 5 to implement an "abstract class" to a class we need to use "extends" keyword.

Interface : In PHP 5 an interface enforces implemented classes to provide all the implementation for function signature.

Abstract Class : In PHP 5 an abstract class enforces implemented classes to provide the implementation for only abstract functions.

Interface : We cannot declare member variables inside an interface scope.

Abstract Class : We can declare member variables inside an abstract class scope.

So hey friends this is complement story on the object oriented programming concepts in PHP. If you have any doubts or queries please feel free to ask throught the comment section and If you like this article then please share it with your friends on google+, facebook.

Please share this article on your social media network. This article helpful for a developer/programmer for preparing an interview and as well as understanding complete oops concepts.

Author: Gurunatha Dogi

Gurunatha Dogi

Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more

Comments

64x64
By Yash Gupta on 2019-03-02
A very good Article for New Student's Who are searching for OOPS concepts but can't find any resources on various Websites. Thank you dear.
64x64
By Suresh Kumar on 2014-12-23
nic article,
64x64
By Ananth on 2014-11-27
very useful article.

Add a Comment