Object-oriented programming (OOP) is an important technique regardless of the programming language developers use, and PHP is no exception. This article will discuss 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 has become popular because of its simplicity. PHP code can be combined with HTML code and once the PHP code is executed, the web server sends the resulting content in the form of HTML or images that can be interpreted by the browser. We all know the power and importance of object-oriented programming or OOP. This is a technique that is widely used in the modern programming languages.
Common OOP Concepts Used in PHP
Inheritance – Inheritance is the most important concept of Object-oriented programming used in most common programming language. Inheritance is based on the principle of parent and child classes. 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 add a few more properties.
Listing 1 – Sample code to show inheritance
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
}
}
In the code snippet above 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 includes the concept of Public, Private and Protected access modifiers.
• 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 – The overloading feature enables us to have two methods with same name but with different parameters. Shown in the following code snippet:
Listing 2 – Sample code to show overloading
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 ";
}
}
}
In the code above, we have two methods with 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.
Note of clarification added after original article post date:
In the above example, we 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.
function myTestFunction()
{
print_r(func_get_args());
}
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.
myTestFunction ();
myTestFunction ("Hello");
myTestFunction ("Hello","Dear");
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.
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";
}
Accessors and Mutators – Commonly known as getters and setters, or Accessors and Mutators, are widely used in every programming language. Accessors (or getters) are functions that are used to return or get the value of the class level variables. Mutators (or setters) are functions that 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
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;
}
}
These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.
Static – Using a 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 an instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods you must take care that the $this variable is not allowed within a static method.
Listing 4 – Sample code for static keyword and method
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;
}
}
Abstract Class – In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can’t be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – ‘abstract’.
Listing 5 – Sample code for Abstract Class
abstract class testParentAbstract {
public function myWrittenFunction() {
// body of your funciton
}
}
class testChildAbstract extends testParentAbstract {
public function myWrittenFunctioninChild() {
// body of your function
}
}
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, the interface is a collection of definitions 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 in any other language. First we need to define the interface using the keyword – ‘interface’. When implementing, we just need to mention the ‘implements’ keyword in the implementing class.
Listing 6 – Sample Code for Interface
interface myIface {
public function myFunction($name);
}
class myImpl implements myIface {
public function myFunction($name) {
// function body
}
}
Summary
PHP has emerged as one of the most popular languages for web application development. It has been enhanced to support different aspects of programming and of those, the object-oriented features are the most important to understand and implement.
About the Author
Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies. You can find more of his work at www.techalpine.com and you can email him here.