Implementing Interfaces: PHP OOP


Video tutorial illustrates the concept of implementing interfaces in Object Oriented PHP.

We also show you, how it over comes the ambiguity issue of multiple inheritance.

Interfaces acts as placeholder or the blueprint for what you can create.
Interfaces provide the basic design for a class with zero implementation detail.
Interfaces define what methods a class must have ..and you can create other methods outside of these limitations too.

extend and implement
interface.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
< ?php
class A
{
public function display()
{
echo "I love Apple Products";
}
}
 
interface I
{
const COMPANY = "Technotip.com";
public function company();
public function display();
}
 
class B extends A implements I
{
function company()
{
echo "I Love BuySellAds and Technotip.com";
}
 
function display()
{
echo "Microsoft & Oracle";
}
}
 
$obj = new B();
$obj->company();
?>

This would output I Love BuySellAds and Technotip.com

Accessing Constant Variable
To access the constant variable present inside interface, use the class name followed by scope resolution operator and then the constant variable name:
B::COMPANY

Implementing Interfaces: PHP OOP



YouTube Link: https://www.youtube.com/watch?v=iOfpmXph5EU [Watch the Video In Full Screen.]



In multiple inheritance you have two parent classes. If both of them have a method with same name, signature and you don’t even override it in the child / derived class, then PHP engine will have no way to know which method to use.

multiple-inheritance-classB-classC-to-classA


In interface, you HAVE TO (must) override the methods present in interface class while implementing it. Hence solving the ambiguity issue.

Note:
All methods declared in an interface must be public.
All variables in interface must be constant.
Interfaces cannot be instantiated.
Object Oriented PHP only supports Single Inheritance. i.e., you can have only one parent class.
You can implement more than one interface. Use comma separation to implement more than one interfaces.

Ex 1:
interface A { }
interface B { }
class C implements A, B { }

Ex 2:
class D { }
interface A { }
interface B { }
class C extends D implements A, B { }

Leave a Reply

Your email address will not be published. Required fields are marked *