TechAlpine – The Technology world

How to write Advanced Object-Oriented Programming in PHP?

OOP PHP

OOP PHP

Overview: Object Oriented programming (OOPs) is an important technique regardless of the programming language we use. And hence, PHP is not an exception in this.

In this article we will talk about how to develop advanced object oriented programs in PHP.

Introduction: PHP is a server side scripting language used to develop web pages. In the recent times PHP is becoming popular because of its simplicity. PHP code can be combined with HTML code. Once the PHP code is executed, the web server sends the resulting content in the form of HTML or images which can be interpreted by the browser.  We all know the power and importance of object oriented programming or OOPs. This is a technique which is widely used in the modern programming languages.

Common OOPs concepts used in PHP:

Let us talk about some common object oriented concepts which are used in PHP:

  • Inheritance – Inheritance is the important concept of Object oriented programming used in most common programming language. Inheritance is based on the principle of parent and child class. In PHP we achieve inheritance by extending the class. By extending a class the child class inherits the properties of the parent class and additionally we can have few more properties. Let us consider the following sample code –

Listing 1 – Sample code to show inheritance

[Code]

class Employee {

public $firstName = “”;

public $lastName = “”;

public $eCode = “”;

public $dept = “”;

 

public function dailyCommonTask() {

// Code for routine job

}

}

class Accountant extends Employee {

public function processMonthlySalary($eCode) {

// Code for processing salary

}

}

[/Code]

In the above code snippet we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant’s job to process the salary of other employees.

  • Public, Private and Protected – As in any object oriented language, PHP also has the concept of Public, Private and Protected access modifiers. Below mentioned is the feature of these three –
    • Public – With having public access the code is visible and can be modified by any code from anywhere.
    • Private – With having private access the code is visible and can be modified from within the class only.
    • Protected – With having protected access the code is visible and can be modified from the same class or any of its child class.
  • Overloading – Overloading feature enables us to have two methods with same name but with different parameters. Let us see the following code snippet –

Listing 2 – Sample code to show overloading

[Code]

class Accountant extends Employee {

public function processMonthlySalary($eCode) {

// Code for processing salary

}

public function processMonthlySalary($eCode, $variablePayFlag, $variablePercentage) {

if($variablePayFlag) {

echo “Please process the salary with variable pay “;

} else {

echo ” Please process the salary without variable pay “;

}

}

}

[/Code]

In the above code, we have two methods having the same name – ‘processMonthlySalary’. In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches –

  • With variable pay
  • Without variable pay

While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component.

In the above example, we have explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args () is used inside a PHP function which holds all the arguments (as an array) passed into it. So the same function can be called with different arguments.

For example, let us take a function called myTestFunction () and we want to use it as an overloaded function.

[code]

function myTestFunction()

{

print_r(func_get_args());

}

[/code]

Now, multiple calls to this function could be as shown below. The func_get_args () will have all the arguments which can be used as per requirement. The first call does not pass any argument, the second call passes one argument and the third one sends two arguments. So the function is acting as an overloaded function.

[code]

myTestFunction ();

myTestFunction (“Hello”);

myTestFunction (“Hello”,”Dear”);

[/code]

There is also another way of implementing overloading in PHP by using __call() and __callStatic() methods.

For example, the code snippet below shows the arguments passed into it along with the method name. Here $name is case sensitive. The output will print the method name and the arguments passed into it.

[code]

public function __call($name, $arguments)

{

echo “We are calling in object context ‘$name’ ”

. implode(‘, ‘, $arguments). “\n”;

}

public static function __callStatic($name, $arguments)

{

echo “We are calling in static context ‘$name’ ”

. implode(‘, ‘, $arguments). “\n”;

}

[/code]

  • Accessors and Mutators – Commonly known as getters and setters, Accessors and Mutators are widely used in every programming language. Accessors or getters are functions which are used to return or get the value of the class level variables. Mutators or setters are functions which are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example –

Listing 3 – Sample code for Accessors and Mutators

[Code]

class Employee {

public $firstName =  “”;

public $lastName = “”;

public $eCode =  “”;

public $dept = “”;

public function getfirstName() {

return $this->firstName();

}

public function setfirstName($firstName) {

$this->firstName = $firstName;

}

public function getlastName() {

return $this->lastName();

}

public function setlastName($lastName) {

$this->lastName = $lastName;

}

public function getECode() {

return $this->eCode();

}

public function setECode($eCode) {

$this->eCode = $eCode;

}

public function getDept() {

return $this->dept();

}

public function setDept($dept) {

$this->dept = $dept;

}

}

[/Code]

These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.

  • Static – Using static keyword for both variable and method is a common practice in object oriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods it must be taken care that the $this variable is not allowed within a static method. Let us see the following example –

Listing 4 – Sample code for static keyword and method

[Code]

class StaticSample {

public static $my_static = ‘Sample Static variable’;

public function staticValue() {

return self::$my_static;

}

public static function aStaticMethod() {

echo “This is the Hello message from static method”;

}

}

class StaticShow extends StaticSample {

public function checkStatic() {

return parent::$my_static;

}

public function checkStaticMethod() {

return parent::$aStaticMethod;

}

}

[/Code]

  • Abstract Class – In PHP, these two features of object oriented programming are used very frequently. Abstract classes which can’t be instantiated rather they can be inherited. The class which inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – ‘abstract’. Let us see the following code snippet –

Listing 5 – Sample code for Abstract Class

[Code]

abstract class testParentAbstract {

public function myWrittenFunction() {

// body of your funciton

}

}

class testChildAbstract extends testParentAbstract {

public function myWrittenFunctioninChild() {

// body of your function

}

}

[/Code]

In the above example, we can create an instance of the child class – testChildAbstract, but we can’t create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

  • Interface – In object oriented programming, Interface is a collection of definition of some set of methods in a class. By implementing an interface, we force the class to follow the methods defined in the interface. In PHP, interface is defined like any other language. First we need to define the interface using the keyword – ‘interface’. While implementing we just need to mention the ‘implements’ keyword in the implementing class.

Listing 6 – Sample Code for Interface

[Code]

interface myIface {

public function myFunction($name);

}

class myImpl implements myIface {

public function myFunction($name) {

// function body

}

}

[/Code]

Summary: PHP has emerged as one of the most popular language for web application development. It has been enhanced with advanced features to support different aspects of programming. Object oriented features are the most important to understand and implement. In our discussion we have covered it in details.
Let us conclude our discussion in the form of following bullets –

  • OOP is a technique which is used almost in all programming languages.
  • In PHP we have all the commonly used object oriented programming concepts as below –
    • Inheritance
    • Overloading
    • Accessors & Mutators
    • Public, Private, Protected, Static
    • Abstract classes and Interfaces

 

 

 

 

Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 1 = 5

TechAlpine Books
-----------------------------------------------------------