PHP Abstract Class and Interface

Abstract class

Abstraction is a way of hiding information .

In abstraction there should be at least one method which must be declared but not defined.

The class that inherit this abstract class need to define that method.

There must be a abstract keyword that must be return before this class for it to be abstract class.

This class cannot be instantiated . only the class that implement the methods of abstract class can be instantiated.

There can be more than one methods that can left undefined.

<?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 a abstract class and it contains a abstract method b().
the child class m inherit class a in which abstract method be is defined completely.

<?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 interface.

Any class that implement this interface must use implements keyword and all the methods that are declared in the class must be defined here. otherwise this class also need to be defined as abstract.

Multiple inheritance 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 above example there are two interfaces A and B. a class c implements both interfaces and define the methods f1() and f2()
of interfaces A and B respectively. if any of the method of interfaces are left undefined in the class that implements the interface then
it must be defined as abstract.

Leave a comment