Inheritance and Interfaces in PHP

Coding (Php 7.x)


Learn how to use create relationship in Object-Oriented Programming
 
/img/blog/inheritance-and-interfaces-in-php.jpg

Follow the series ...

 

This blog post is the second part of  "The complete guide to Object-Oriented Programming: Go from procedural programming to OOP expert in PHP"

 

If you did not read the other parts yet

You can check the other blog posts following the links below 
Introduction to Object-Oriented Programming
Inheritance and Interfaces in PHP
More Interfaces and Polymorphism
Visibility and Static keyword
Constructor and Magic methods and  
Abstract Classes and Extra bits 

 

Introduction

Once upon the time, 


there was a Web Developer who used to spend weeks and weeks updating the same lines of code.


This caused him very bad headaches.

 

One day browsing between blogs' post he came across the words Object Oriented Programming and what happened next is astonishing...

 

 

In the previous post, you discovered the basics of the OOP paradigm in PHP,

 

From its simple syntax to the advantages of reusing the same code in a straightforward still powerful way.


Today you will learn how to best manage these objects and create long and safe relationships among them using inheritance and interfaces.
 

 

Inheritance

What are inheritances on OOP?

We are now entering in one of the 4 basic pillars of Object Oriented Programming in PHP.

Inheritance alongside encapsulation, abstraction, and polymorphism need to be mastered to become proficuous in programming and really improve your skills.

 

What inheritance does is relate classes to each other in a parent-child model.

 

This is very useful when extraction characteristics that the related classes must have in common and allow to implement further methods and properties without rewrite the same again.

 

Like the last post let’s still use the Building class as an example,
In this example, we are presuming that when you want to instantiate a new building the work to build it have been completed and it is open to the public. 


class Building 
{
    $inCostruction = false; 
    $isOpen = true;

    function closeBuilding()
    {
        return $this->isOpen = false;
    }
    function openBuilding()
    {
        return $this->isOpen = true;
    } 
}

class School extends Building
{
}

class Office extends Building
{
    $isOpen = false;
}

 

 

We have three classes here,

the parent class which is the Building class and its children that inherit the building features, both properties, and methods.

We can now instantiate specific Schools and Offices rather than an abstract class Building


  

$mySchool = new School();
$myOffice = new Office();
echo $myShool->closeBuilding(); // The output will be “false” because of the parent Building
echo $myOffice->isOpen; // The output will be “false” because of the child Office

 

As you can see I haven’t actually written anything inside the School class but it still inherits all the property and methods of its parent class Building.


This principle is called DRY (Don't repeat yourself) and its goal is to reduce the text we write time and time again.

 

I am sure you have also notice that the Office class has a different value on the $isOpen variable than its parent,

in fact,

by writing the same property or method in the of the parent into the child we overwrite its functionality.

 

Basically,

when instanciated $myOffice is closed instead $mySchool follow the behavior of Building and remain $isOpen remain false ($mySchool is open to visit).

 


Why use inheritance?

There are several currents of thought about this topic,

someone says inheritance is good, some senior developer will kill you if you just think to use it in a live project, 


I think that as most of the time the truth stays in the middle.

Inheritance is an amazing way to save time avoiding to write the same things over and over again,

it is very simple to understand and for a novice in OOP is the right path to follow.


It is also true that inheritance has several limitations and for an experienced web developer, there are quite a few better choice, one upon all composition.

Have a look at this video from Fun Fun Function

 

 

 

My advice is to use inheritance as long as you are 100% comfortable with this technique, you understand how to use it, when to use it to share functionalities and when instead use other technique like composition, design patterns (the factory pattern is a really close case), or even just add a trait to the class.

 


The extends keyword

Nobody knows why the keyword to create inheritance is not inherits or something more consistent and easy to remember but here we are.


To allow a class inherits from another class we need to specify the keyword "extends" and the parent class just after the name of the child class and before the opening braces.

 

A situation to be careful about is that a child class must always depend only on a single parent class, which mean multiple inheritances is not supported.


Think about it in this way:
The Office class we use in the previous example cannot inherit features from the Building class and the Animal class in the same moment. 


They just have no characteristics in common.

 


The “final” keyword

The final keyword is are really easy concept introduced for the first time in php5.


In simple words,

it prevents method or classes to be extended.

Let’s see a quick example.

 

Presume that the mayor of our imaginary city decided that all the building must have at least an emergency exit and now look at the following sample of the code.

class Building 
{
    ...
    function setFireExtinguisher()
    {
        $this->fireExtinguisherCount = 1;
    }
}

class Office extends Building
{
    function setFireExtinguisher()
    {
        $this->fireExtinguisheCount = 0;
    }
}


 

In this case,

the setFireExtinguisher() method of the Office class has overwritten the Building class and set the fireExtinguisheCount to 0,


Which as the mayor decided it is illegal.


A way to prevent it and avoid the architects to go to jail it to add the final keyword to the method.     

class Building 
{
    ...
    final function setFireExtinguisher()
    {
        $this->fireExtinguisherCount = 1;
    }
}

class Office extends Building
{
    function setFireExtinguisher()
    {
        $this->fireExtinguisheCount = 0;
    }
}


 

Now the code of the setFireExtinguisher() method of the Office class cannot be used and it will actually result in a Fatal error “Cannot override final method Building->setFireExtinguisher()".

Very simple concept, very easy implementation.


There is only a rule in this section of the article:

You cannot use final on attributes.

 

Attributes are variables and as the name suggests they need to be able to vary.

 

You can use final on classes that you do not want to be extended or methods that must not be overwritten.

 


Interfaces

What are the mandatory steps that architects and constructors need to follow in order to create a building?


There are several regulations the need to be followed especially in public areas such us add several first aids, set evacuation plans up, etc.

An interface lets you arrange this steps in advance and oblige the classes to implement them accordingly.


In a very simplistic way if a class is a blueprint of an object you can think of an interface like a blueprint for classes.


Think at Interface as a pure template.

Let me explain,

Why do you need object interfaces in the first place?


in PHP Interfaces define which methods a class must implement, 


At the same time interfaces do not specify how these methods need to be implemented,


you will see soon that the last sentence gives you a lot of freedom when managing your classes.

 

 


The “interface” keyword

The syntax to create interfaces is almost the same as the one to create classes,


Naming an interface usually follow some conventions that will make it easier for others to understand your code, the most used convention are:

 

  • ThingInterface;
  • IThing;
  • I_Thing;

 

In the following example, I am going to create interfaces that I will use in the Building class.

 

The already-famous mayor of our city is very concerned about security and he decided that every building in our city must have a fire alarm and an assembly point in case of calamity.

 

Let’s code those interfaces.

interface FireAlarmInterface 
{
    function setFireAlarm();
}
interface AssemblyPointInterface 
{
    function setAssemblyPoint();
}


 

There are two things that you should notice in the previous snippet,


the first one is that interfaces look very similar to classes, 


the second is that there are no braces that open the block of code in the methods, the reason is that interfaces do not determinate how methods need to be implemented they just determinate what methods need to be implemented.

 

 

The “implements” keyword

Now that the interfaces have been created we need to implement them in our Building class.


To implement an interface you need to use the implements keyword.


A fundamental particularity important that you have to take note about is that: all the methods in the interfaces must be included in the classes that implement the interface.


This is a mandatory rule, and there is no exception;


PHP will let you know if you forgot methods by throwing a fatal error on the screen. 

class Building implements FireAlarmInterface
{
    function setFireAlarm()
    {
        $this->fireAlarm = true;
    }
}


As said, all methods in the interface must be implemented within a class;

failure to do so will result in a fatal error. 


Unlike inheritance, a class may implement more than one interface.


In fact,

if desired you can list as many interfaces as you like by listing them and separate each interface with a comma.

 

class Building implements FireAlarmInterface, AssemblyPointInterface 
{
    …
}


Although this is a very impressive feature of PHP, let me highlight once again that each method of each interface implemented must be included within the class and this can lead to a lot of disorder.


So be parsimonious with your interfaces and use them only after you have studied all the incoming problems that can take place.

 

 

List of built-it interface included in PHP

PHP has a handful of interfaces integrated into the language.


Although the majority of them will be unlikely to be used on a day to day basis some could be very useful and will definitely save you some time during the development process of your project.

 


Traversable

As the name suggests the Traversable interface analyzes a class and return a boolean value depending if the class that is implementing the traversable using a foreach.

This interface has no methods, its intent is to be a foundation for traversable classes.

Traversable {
}


 

You can use this interface in your conditional statement to check if something is usable if a foreach.

Here is a quick example

if( $buildings instanceof Traversable ){
    foreach ($buildings as $building){
        …
    }
}


 

Notice that the interface does not work on arrays and objects, 
which means you cannot user Traversable to check if a variable of these types can be used in an array.

Why do you even need to verify them in the first place?

 

 

Iterator

This interface works on object or iterators that can repeat themselves.


The sentence above simply means that you can extend the Iterator interface to whichever element that is traversable and include the following methods on the class. 

Iterator extends Traversable {

    function current ()
    {
    }
    function key ()
    {
    }
    function next ()
    {
    }
    function  rewind ()
    {
    }
    function valid ()
    {
    }
}


Understood??
Here There is a real sample of how this interface might be really used for:

public function rewind() 
{
    $this->position = 0;
}
public function current() {
    return $this->array[$this->position];
}
public function key() {
    return $this->position;
}
public function next() {
    ++$this->position;
}
public function valid() {
    return isset($this->array[$this->position]);
}


 

IteratorAggregate

The IteratorAggregate interface is simply another method to implement an Iterator in your code.

IteratorAggregate extends Traversable {
    function getIterator ()
    {
    }
}



The benefit of using this interface is the speed,


In fact, IteratorAggregate is much faster than other options,


you need to notice that despite the name this is not an Iterator but it is a Traversable.
which means there are no next, key, current, valid, rewind methods available.
 

 

Throwable

The Throwable interface is used for all the objects that can be thrown via the throw statement,
They include Errors and Exception.
Here is the interface and its complete list of methods:

interface Throwable {
    function getMessage ()
    {
    }
    function getCode ()
    {
    }
    function getFile ()
    {
    }
    function getLine ()
    {
    }
    function getTrace ()
    {
    }
    function getTraceAsString ()
    {
    }
    function getPrevious ()
    {
    }
    function __toString ()
    {
    }
}

PHP cannot implement this interface directly,

it can only be extended via Exception.

 

 

Conclusion of second part

 

The full version of "The complete guide to Object-Oriented Programming" in an all-in-one edition is available in a Kindle format on Amazon

 

However do not worry, the following parts will be published in the following weeks.

 

 

... The Web Developer truly believed that he was very good in his job, and to be honest he was right.

 

He was already able to create everything passed from his mind, he could create applications from scratch and even difficult systems that make his boss and his clients happy,

 

What he realized is that his field is a no-stop learning, and after one thing there is another, then another, then another.

 

Today you are like him, 

you have learned the OOP basics, now you know some more keywords, tomorrow you'll soak in other information.

 

Programming never ends, the less you think you know the better you become.

 

In which part of your development knowledge are you?
Do you already learn everything or you just step in OOP principles?

 

Let me know in the comment below...

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Oct 1, 2018

The complete guide to Object-Oriented Programming

Master OOP See details
Coding (Php 7.x) Oct 15, 2018

Interfaces and Polymorphism in PHP

Get a Copy See details
Coding (Php 7.x) Oct 22, 2018

Visibility and Static keyword in PHP

Improve your Skills See details
Get my free books' review to improve your skill now!
I'll do myself