Codementor Events

Abstract vs Interface (oop in PHP)

Published Sep 12, 2019
Abstract vs Interface (oop in PHP)

An abstract class can't be instantiated, yes it is a class however no one is allowed to instantiate, but since we cannot instantiate it we would have to create a subclass that inherits the abstract class.

<?php
abstract class exampleAbstract {
}
class exampleClass extends exampleAbstract {
}

However there is also an abstract method, we can use an abstract class to create an abstract protected method. More so this abstract method that can only be created using an abstract class, must be used by all the subclasses that inherit the abstract class. So all the classes that inherit the abstract class have to make use of the method in their own different versions of the same method.

<?php
abstract class exmapleAbstract {
abstract protected function exampleMethod();
}
class exampleClass extends exampleAbstarct {
abstract protected function exampleMethod()
{
return  ' ';
}

An interface is like a contract that defines a public API, so it defines a contract that every class that implements it ahs to abide by the contract. However no logic can ever be stored within an interface, this makes it very cheap to use. An interface doesn't need to be inherited by a class that needs to use its method but instead, it has to be implemented.

<?php
interface exampleInterface {
public function exampleMethod();
}
class exampleClass implements exampleInterface {
public function exampleMethod()
{
return ' ';
}

Discover and read more posts from Nwoga kingsley
get started
post commentsBe the first to share your opinion
Show more replies