Interfaces are a set of instructions for your class. When you implement an interface, the inheriting class must follow the rules defined by the interface.
Interfaces include a list of all methods and properties that your inherited class must have, their arguments, types and any PHP documentation. They serve two key purposes: provide a set of instructions for a developer who is extending the parent class, and a set of rules for the extended class to follow.
A great scenario for use is if your creating a class that will be accessed or expanded in the future by other classes. In my case, I use Interfaces often when creating APIs, like Restful or SOAP APIs. The base class is concrete and contains some important required tools, so the interface tells my other developers how they can interact with the parent class.
A Valid use of Interface
interface MyInterface {
/**
* This method is required in your inheriting class
* @var \stdClass $MyRequiredParameter - A object of options
*/
public function myRequiredMethod(stdClass $MyRequiredParameter);
}
class MyClass implements MyInterface {
public function myRequiredMethod(\stdClass $MyRequiredParameter)
{
return $MyRequiredParameter->MyValue;
}
}
class MyExtension extends MyClass implements MyInterface {
public function myRequiredMethod(\stdClass $MyRequiredParameter)
{
return $MyRequiredParameter->MyOtherValue;
}
}
Example of an Invalid Extension of a Interfaced Class
class MyBadExtension implements MyInterface {
public function weDontNeedNoStinkingRequiredMethods()
{
return FALSE;
}
}
Since we didnt follow the pattern of the interface, we generate a fatal exception:
Fatal error: Class MyBadExtension contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (MyInterface::myRequiredMethod)