Inheritance, Encapsulation, Abstract Class and Interface in PHP 7

In Dictionary if you search the word ‘inheritance’, you’d land up finding this kind of description: …objects that someone gives you when they die.
In the programming world, it does not mean exactly the same in every sense but almost same if you take the literal meaning. Yes, there is a parent class with one or more child classes who inherit the objects from their parents but child classes are freer here, in the php programming world. These child classes are free to modify or override the properties and methods that they inherit. In real world it does not happen always.
Let us a have a simple code to check a parent class and child class.

//Day2/inheritance.php
name = $name;
}
public function getWeight() {
return $this->weight;
}
public function setWeight($weight) {
if ($weight > 2){
throw new Exception;
}
$this->weight = $weight;
}
}
//child class Guitar
class Guitar extends Instrument {
}
$guitar = new Guitar('Electric Guitar');
$guitar->setWeight(1);
$guitar->getWeight();
var_dump($guitar);

The output is as expected.

object(Guitar)#1 (2) {
["name":protected]=>
string(15) "Electric Guitar"
["weight":protected]=>
int(1)
}

The child class ‘Guitar’ has inherited each property from its parent class ‘Instrument’. When you create a guitar instance it automatically inherits every property.
This situation may not persist all along. We could have many child classes all together that inherit the properties and methods of the parent class but want to behave on their own way. Everyone wants freedom, isn’t it?
In such cases, a ‘Spanish Guitar’ class may not agree with the weight of an ‘Electric Guitar’ class. A Spanish guitar may want to be lighter than an Electric guitar. In such case a child class should have an ability to override the methods of the parent class that have a definite algorithm to set the weight.
Let us see how we can solve this problem.


//Day2/instrument.php
name = $name;        
    }    
    public function getWeight() {
        return $this->weight;
    }    
    public function setWeight($weight) {
        if ($weight > 2){
            throw new Exception;
        }
        $this->weight = $weight;
    }    
}
class SpanishGuitar extends Instrument {
    
    public function getWeight() {
        return $this->weight;
    }    
    public function setWeight($weight) {
        if ($weight > 2){
            throw new Exception;
        }
        $this->weight = $weight;
    }
}
class ElectricGuitar extends Instrument {
    
    public function getWeight() {
        return $this->weight;
    }    
    public function setWeight($weight) {
        if ($weight > 10){
            throw new Exception;
        }
        $this->weight = $weight;
    }
}
$spanish_guitar = new SpanishGuitar('Spanish Guitar');
$spanish_guitar->setWeight(1);
$spanish_guitar->getWeight();
var_dump($spanish_guitar);
$electric_guitar = new ElectricGuitar('Electric Guitar');
$electric_guitar->setWeight(8);
$electric_guitar->getWeight();
var_dump($electric_guitar);

Let us first run this code and see the output.

object(SpanishGuitar)#1 (2) {
["name":protected]=>
string(14) "Spanish Guitar"
["weight":protected]=>
int(1)
}
object(ElectricGuitar)#2 (2) {
["name":protected]=>
string(15) "Electric Guitar"
["weight":protected]=>
int(8)
}

As expected. In our code, we have two child classes – Spanish Guitar and Electric Guitar. Each one has its own weight criteria. A Spanish Guitar should come out lighter than an Electric Guitar. Hence, the algorithm changes inside them. They just override their respective parent method.
# Introducing Abstraction and Encapsulation
These two features are very important for any object oriented programming language. Abstraction involves extracting only the relevant information. Encapsulation means packaging one or more two components together.
## Defining Abstraction
A car salesman always gives relevant information to a potential customer. He knows that different people have different preferences. Keeping that in mind he only presents and stresses specific feature to a potential customer. Although all customers want to buy a car bur some of them consider the price first, some search for a specific color, some are interested on engine and speed – actually each of them has a specific point of interest. A good salesman always follows that trend and presents only the relevant part.
This is the core concept of abstraction or abstract classes. The information is hidden but not unavailable. All information exist but only the relevant ones are presented.
## Defining encapsulation
Encapsulation literally means ‘enclosing some information in a capsule or package’. For example when we switch on the car engine, we do not see the complex processes going on inside the bonnet. How battery, fuel, engine work together remains encapsulated. We can, for that reason, say that encapsulation is also explained as data hiding or information hiding.
## Difference between Abstraction and Encapsulation
They are different but related. You encapsulate information into a package and abstraction enables you to present relevant information from that package.

## Abstract Classes

Considering the previous codes we have used before, we’re still not contented with this design pattern because, as you see in the code, we had to overuse our methods extensively. It is working fine, no problem, but we want more flexibility in our code.
Consider this code.


//Day2/abstract_instrument.php
name = $name;
        return $this->name;        
    }    
    public function getWeight() {
        return $this->weight;
    }    
    public function setWeightforSpanish($weight) {
        if ($weight > 2){
            throw new Exception;
        }
        $this->weight = $weight;
    }
    public function setWeightforElectric($weight) {
        if ($weight > 10){
            throw new Exception;
        }
        $this->weight = $weight;
    }    
}
class SpanishGuitar extends Instrument {
}
class ElectricGuitar extends Instrument {
}
$spanish_guitar = new SpanishGuitar('Spanish Guitar');
$spanish_guitar->setWeightforSpanish(2);
$spanish_guitar->getWeight();
var_dump($spanish_guitar);
$electric_guitar = new ElectricGuitar('Electric Guitar');
$electric_guitar->setWeightforElectric(8);
$electric_guitar->getWeight();
var_dump($electric_guitar);

The previous code had 49 lines of code. And the modified version of that code has got 37 lines. We are able to reduce 12 lines of code and at the same time we also make our codes more readable and modular. The only difference is we declared our parent class abstract. What the heck is it?
Imagine something abstract that transcends into the child classes as the lineage. Exactly same thing happens here. We can even modify our child classes by adding more methods to it.
Let’s change that part and see the output.

class SpanishGuitar extends Instrument {
public function run() {
echo "You don't need electric.";
}
}
class ElectricGuitar extends Instrument {
public function run() {
echo "You need electric.";
}
}
$spanish_guitar = new SpanishGuitar('Spanish Guitar');
$spanish_guitar->setWeightforSpanish(2);
$spanish_guitar->getWeight();
$spanish_guitar->run();
var_dump($spanish_guitar);
$electric_guitar = new ElectricGuitar('Electric Guitar');
$electric_guitar->setWeightforElectric(8);
$electric_guitar->getWeight();
$electric_guitar->run();
var_dump($electric_guitar);

The output is like this.

You don't need electric.object(SpanishGuitar)#1 (2) {
["name":protected]=>
string(14) "Spanish Guitar"
["weight":protected]=>
int(2)
}
You need electric.object(ElectricGuitar)#2 (2) {
["name":protected]=>
string(15) "Electric Guitar"
["weight":protected]=>
int(8)
}

The only problem of an abstract class is that, it does not support instantiation and its method should not be left empty. To overcome this difficulty the concept of interface has come up as huge help.

## Basic Interfaces

Interfaces are also called contracts. It actually defines the syntactical contract that all the derived classes should follow. Let us consider an example first to understand how this contract works.

interface InputOrderDetails {
public function UpdateCustomerStatus();
public function TakeOrder();
}
class ItemDetails implements InputOrderDetails {
public function UpdateCustomerStatus(){
var_dump("Updating customer...");
}
public function TakeOrder(){
var_dump("Taking orders..");
}
}
$item1 = new ItemDetails;
$item1->TakeOrder();
$item1->UpdateCustomerStatus();

We have an interface which defines a syntactical contract and the class follows those contracts exactly as it has been defined.
Look at the output.


string(15) "Taking orders.."
string(20) "Updating customer..."

Now we can move forward this contract to furthermore. We can imagine a situation where we can use our interface concept to hide information. Consider the contract between the seller companies a buyer. The buyer does not know how the product reaches to her. Besides, the seller also does not want to accept the responsibility of carrying the product on its own to the house of the buyer. So the company gives that responsibility to a courier company. Now the courier receives the product from the seller and carries to the buyer.
In this scenario, the courier does not know what type of product it’s carrying to the buyer. We follow the SOLID Design principle exactly as we have wished to do.
Let us see the code, it tells a relationship and messaging between many objects.


deliverer = $deliverer;        
    }
    public function recieve() {
        $user = "Sanjib";
        $this->deliverer->deliver($user);        
    }
}

$user = new User(new Retailer());
$user->recieve();

The ‘Retailer’ delivers the instruction to the ‘Deliverer’. So there is a contract between them and the retailer needs user as a parameter to whom it will send the item. Retailer knows the nature of the item, what item it’s sending; but deliverer doesn’t know about it. The deliverer only delivers and does not know anything. The buyer only receives, so she needs one ‘deliverer object’ who will deliver. Exactly the same thing happens here. Look at the code and the output below.

string(25) "One book sent to...Sanjib"

For further reading…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s