OOP in php

OOP in PHP – Inheritance | Encapsulation | Abstraction | Polymorphism

Before starting this tutorial, please make sure that you have read the Part I of this series.

Let’s move further. Here’s another important OOP concept.

Inheritance

Inheritance is one of the most important aspects of OOP. It allows a class to inherit members from another class. One of the main advantages of object-oriented programming is the ability to reduce code duplication with inheritance. Code duplications occur when a programmer writes the same code more than once, a problem that inheritance strives to solve.
In inheritance, we have a parent class with its methods and properties, and a child class (or classes) that can use the code from the parent. By using inheritance, we can create a reusable piece of code that we write only once in the parent class, and use again as much as we need in the child classes. So, the main idea of the inheritance is, we can access the properties of other class rather than write the same code again. To quickly understand the concept of inheritance, think it as just like a newborn baby who has the properties of her parent.

INHERITANCE

To implement inheritance,  we made one class and define some methods in it, then we create another class and inherits it from the first class. By inheriting the new class from the first class, we can use the methods written already in the first class into the new class. The class from which the other class(es) inherits is called the parent class, and the inherited classes are called child classes.
Let’s see the code implementation of inheritance in PHP.

The parent class:

class ParentClass
{
    //define variable
    private $data1;
    //Function/behavior
    function parentFun()
    {
       echo “I am the function of parent class”;
    }
}

The child class:

To create a class as a child, we use the keyword “extends” after the class name, followed by the name of the parent class. See the code below.
The child class:

class ChildClass extends ParentClass
{
    function childFun()
    {
        echo "I am the function of child class.";
    }
}

Let’s create an object of the child class and call its method “childFun”.

$child1 = new ChildClass();
$child1->childFun();

The above code will display the output “I am the function of child class”.
To call the method of its parent class, we just call it just like we call its method. 

$child1->parentsFun();

The above code will display the output “I am the function of parent class”.
A real-life example of inheritance is Vehicle-Car example, where the Vehicle is a parent class, and the Car is a child class. Some other real-life examples could be, Shape-Circle, Pet-Cat and/or Employee-Manager.
The relationship between a parent and a child class is called “is-A’ relationship. For example, Car is a Vehicle, and Circle is a shape etc. 

Overloading and Overriding methods:

Overriding in PHP is same as other programming languages, but overloading is quite different.

Method Overriding:

We already know that when we inherit a child class from a parent class, the child class has access to the methods of its parent class. Let’s say we have an Animal class with a method move(). The following code is the implementation of this class.

class Animal{
  public function move(){
    echo "The animal is moving.";
  }
}

Now, we want to make the Cat class a child of Animal class. The cat class will inherit the move method as well. Now the problem is, the move method of cat is so generic that it is saying “The animal is moving”, we want to make a specialised version of move method for the Cat class only, which will tell that “The cat is moving” instead of “The animal is moving”. So, to make the specialised version out of a generalised version, we override the move method in the child class.
The overridden method will have the same header as its parent method, but it has its own implementation. The following code is the implementation of the Cat class along with the overridden move method.

class Cat extends Animal{
  public function move(){
    echo "The cat is moving.";
  }
}

To make use of the overridden move method, let’s create an object of the Cat class and call its move method.

$cat = new Cat();
$cat->move();

The above lines of code will produce the output “The cat is moving”.

Method Overloading:

Method overloading is all about having two or more methods with the same name but with a different number of parameters. Let’s understand this concept with an example.

Suppose we have a class Calculator with a method named add, which accepts two parameters and return the sum of them. See the following code:

class Calculator{
  public function add($a, $b){
    return $a + $b;
  }
}

The method written above will only add two parameters. What if we want to add three numbers together? Obviously, we can create another method and call it “addThree”, but this will confuse the user as the user have to call different methods with different names but the purpose of these methods is the same. To avoid this, PHP, like many other languages, allows us to write the methods with the same name with the distinction in the number of parameters to make them unique.

The following lines of code will have two methods with the same name but with the different number of parameters:

class Calculator{
  public function add($a, $b){
    return $a + $b;
  }
  public function add($a, $b, $c){
    return $a + $b + $c;
  }
}

To call the methods:

$obj = new Calculator();
echo $obj->add(2, 3);
echo $obj->add(2, 3, 4);

The second and third line of the above code will display 5 and 9, respectively.

Please note that the method overloading is only available in the class methods and not in non-class functions.

The simple difference between method overriding and method overloading:

Method Overriding: Same name, the same number of parameters, different body.

Method Overloading: Same name, different number of parameters, and a different body.

Abstract classes and Abstract methods:

  • The abstract classes are those classes which have at least one abstract method, and the abstract methods are those methods which only have the header but not the implementation. Here are some essential points to remember about abstract classes and methods.
  • Abstract classes are used when we want to force the programmer to must provide the implementation of the method declared as abstract in the parent class.
  • An abstract class is a class that has at least one abstract method
    Abstract methods can only have names and arguments and no implementation. Thus, we cannot create objects out of abstract classes; instead, we need to create child classes that add the code into the bodies of the methods.
  • An abstract class can have abstract and non-abstract methods.
  • The abstract classes and methods are created with the keyword “abstract”.

Let’s see the code example:

abstract class MyParentClass
{
  abstract public function anAbstractMethod();

  public function aNoneAbstractMethod()
  {
    echo "I have my own implementation.":
  }
}

Now let’s create a child class:

class MyChildClass extends MyParentClass
{
  public function anAbstractMethod()
  {
    echo "I have to provide the implementation of the abstract method I inherited from the parent class.";
  }
}

Let’s call these methods by creating an object of the child class.

$obj = new MyChildClass();
$obj->anAbstractMethod();
$obj->aNoneAbstractMethod();

The output of the lines above is:

“I have to provide the implementation of the abstract method I inherited from the parent class. I have my own implementation.”

Why we need abstract method and classes:

Let’s consider this with an example. Suppose we are creating a school management system, where we need to store the information about Teacher and Student. We want to create a method in both of these classes which will return the information about Teacher and Student, but the problem is that both classes have different information to return, for example, the teacher has the qualification and experience whereas the student might not have such pieces of information. So, we will first create an abstract parent class which will have an abstract method, let’s call it “getDetail”. Both the Teacher and Student now have to inherit from the parent class and need to override the “getDetail” method and provide their own implementation.

Interfaces

PHP Interfaces allows a user to specify some methods which a class must implement. resemble the Abstract classes and methods, but the difference is that a class can not extend the interfaces; instead, it must be implemented by a class. A class can implement an interface by using “implements” keyword after the class name followed by the interface name. An interface can be defined just like a class, but we will write “interface” instead of “class”. The following lines of code will create an interface:

interface MyInterfaceForAirConditioner{
  public function turnOnAC(){
  }
  public function turnOffAC(){
  }
}

A class can implement an interface as follows:

class AirConditioner implements MyInterfaceForAirConditioner{
  public function turnOnAC(){
    echo "AC turned on.";
  }
  public function turnOffAC(){
    echo "AC turned off.";
  }
}

Here are some essential points about the interface.

  • Interfaces can only have abstract methods, which means they will not have any implementation.
  • An interface can also extend from another interface using the “extends” keyword.
    The abstract methods in an interface must be public.
  • A class that implements the interface must provide the implementation of all the methods written in the interface.

Polymorphism

Polymorphism means the ability to have many forms. Let’s consider this with an example. Suppose a person is a teacher, and he is also studying, so he is a student as well. It means that a person has more than one roles, means, more than one form. Some times he is acting as a teacher, whereas he is acting as a student at some points.
The inheritance is one way to implement polymorphism in PHP. We can create a Person class which will have some common attributes like name, age and CNIC of the person. Then we will create a Teacher class and a Student class which will have their unique attributes. The following piece of code will create these three classes:

<?php
class Person{
   $name;
   $age;
   $cnic;
}
class Teacher extends Person{
   $qualification;
   $roomNumber;
}
class Student extends Person{
   $programName;
   $totalProgramFee;
}
?>

To make two roles or two forms of a person, we can simply create the objects of the respective roles. See the code below for understanding:

$personAsaTeacher = new Teacher();
$personAsaStudent = new Student();

The “personAsaTeacher” will have the details of the person along with the details of its specific role, which is a teacher. Same like the teacher, the “personAsaStudent” will have the details of the same person but with the different information of the student.

Here are some more Tutorial for creating Web Application & CRUD Operations using PHP & MySQL.

Similar Posts