PHP does not support multiple inheritance directly, to implement this we need Interface.
Here method are declared in the Interface body, and the body part of the method is implemented in derived class. Variables are declared as constant and it can not be changed in the child classes.
We use implement keyword to extend this kind of class, at the same time we can implement more than one interface and one interface can be implemented by another interface.
All methods declared in an interface must be public and the variables should be constant.
This is mandatory that we must declare the body part of the method in the derived class otherwise an error message will be generated.
PRIMARY PURPOSES OF AN INTERFACE
- Interfaces allow you to define/create a common structure for your classes – to set a standard for objects.
- Interfaces solves the problem of single inheritance – they allow you to inject ‘qualities’ from multiple sources.
- Interfaces provide a flexible base/root structure that you don’t get with classes.
- Interfaces are great when you have multiple coders working on a project – you can set up a loose structure for programmers to follow and let them worry about the details.
WHEN SHOULD YOU MAKE A CLASS AND WHEN SHOULD YOU MAKE AN INTEFACE?
- If you have a class that is never directly instantiated in your program, this is a good candidate for an interface. In other words, if you are creating a class to only serve as the parent to other classes, it should probably be made into an interface.
- When you know what methods a class should have but you are not sure what the details will be.
- When you want to quickly map out the basic structures of your classes to serve as a template for others to follow – keeps the code-base predictable and consistent.
A. A class can not extend more than one interface.
B. A class can implement more than one interface.
C. An interface can extend more than one interface.
D. An interface can not implement more than one interface.
EXAMPLE
<?php
interface a{
public function test();
}
class b implements a{
public function test(){
echo “Function Test”;
}
}
$b=new b();
$b->test();
?>