Home >>PHP Object Oriented >PHP Abstract and Interface Class

PHP Abstract and Interface Class

Abstract class

Abstraction is a way of hiding information. In abstraction, there should be at least one method that must be declared but not defined. The class that inherit this abstract class need to define that method. There must be an abstract keyword that must be returned before this class for it to be an abstract class. This class cannot be instantiated. only the class that implements the methods of an abstract class can be instantiated. There can be more than one methods that can be left undefined.

Example 1
<?php
abstract class a 
{
abstract function b();
public function c()
{
echo "Can be used as it is";
}
}

class m extends a
{ 
public function b()
{
echo "Defined function b<br/>";
}
}
$tClass = new m();
$tClass->b();
$tClass->c();
?>
Output Defined function b Can be used as it is

in the above example class a is an abstract class and it contains an abstract method b(). the child class m inherit class a in which abstract method be is defined completely.

Example 2

<?php
abstract class A
{
abstract function f1();
function f2()
{
echo "hello";
}
}
class B extends A
{
function f1()
{
echo "hi";
}
}
$ob=new B();
$ob->f1();
?>
Output hi

Interface

The class that is fully abstract is called an interface. Any class that implements this interface must use implements keyword and all the methods that are declared in the class must be defined here. otherwise, this class also needs to be defined as abstract.

Multiple inheritances is possible only in the case of interface.

<?php
interface A
{
function f1();
}

interface B
{
function f2();
}

class C implements A,B
{
function f1()
{
echo "hi";
}

function f2()
{
echo "hello";
}

}
$ob=new C();
$ob->f1();
$ob->f2();
?>
Output hi hello

in the above example there are two interfaces A and B. a class c implements both interfaces and defines the methods f1() and f2() of interfaces A and B respectively. if any of the methods of interfaces are left undefined in the class that implements the interface then it must be defined as abstract.


No Sidebar ads