Deference Between Abstract Class and Interface in PHP

Introduction

In this article I explain the difference between an abstract class and an interface class in PHP. An abstract class is a method that must be declared as abstract (only declared not defined). We can create an object of an abstract class. If we want to use this class we must inherit it. An abstract method does not have any implementations but in an interface class all the methods by default are abstract method (only defined). So in interfaces there cannot be declared variables and concrete methods.

Abstract Class Interface Class
1. In an abstract class methods must be declared as abstract In an interface all the methods must be abstract
2. An abstract class can declared with an access modifier such as public or protected. All declared methods must be public
3. An abstract class can contain variables and concrete methods. Cannot contain variables and concrete methods but constants can be defined
4. In an abstract class we can inherit only one abstract class but multiple inheritance is not supported. Multiple inheritance is possible.

Example

Abstract Class

<?php

abstract class AbstractClass

{

    abstract protected function preName($name);

}

class ConcreteClass extends AbstractClass

{

    public function preName($name, $separator = "-") {

        if ($name == "MCN") {

            $pre = "My";

        } elseif ($name == "MCN SOLUTION") {

            $pre = "GOOD";

        } else {

            $pre = "";

        }

        return "{$pre}{$separator} {$name}";

    }

}

$class = new ConcreteClass;

echo $class->preName("MCN")."<br>";

echo $class->preName("MCN SOLUTION");

?>

Output

Abstract in php.jpg

Example

Multiple Interface Class Inheritance

<?php

interface one

{

    public function a();

}

interface two

{

    public function b();

}

interface three extends one, two

{

    public function c();

}

class four implements three

{

    public function a()

    {

    }

    public function b()

    {

    }

    public function c()

    {

    }

}

?>

Interface with Constant

<?php

interface one

{

    const two = 'Interface Constant';

}

echo one::two;

// This will however not work because it is not allow override constant

class two implements one

{

    const two = 'This is not print';

}

?>

Output

Interface with constant.jpg

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now