An interface allows you to specify a contract that a class must implement. To define an interface, you use the interface keyword as follows.
Interfaces allow you to specify what methods a class should implement.
Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".
Syntax for defining PHP Interface
Like classes are defined using the keyword class, interfaces are defined using the keyword interface followed by the interface name.
<?php
// interface declaration
interface NameOfInterface {
}
?>
And a class uses the implements keyword to inherit from an interface and implement the methods declared in the interface.
<?php
// class declaration
class SomeClass implements NameOfInterface {
}
?>
An interface consists of methods that contain no implementation. In other words, all methods of the interface are abstract methods. An interface can also include constants. For example-
<?php
interface MyInterface {
const CONSTANT_NAME = 1;
public function methodName();
}
?>
When you define a class (child class) that reuses properties and methods of another class (parent class), the child class extends the parent class.
However, for interfaces, we say that a class implements an interface.
A class can inherit from one class only. However, it can implement multiple interfaces.
To define a class that implements an interface, you use the implements keyword as follows:
<?php
interface MyInterface {
const CONSTANT_NAME = 1;
public function methodName();
}
class MyClass implements MyInterface {
public function methodName() {
// ...
}
}
?>
When a class implements an interface, it’s called a concrete class. The concrete class needs to implement all the methods of the interface.
Like a class, an interface can extend another interface using the extends keyword. The following example shows how the Document interface extends the Readable interface.
interface Readable {
public function read();
}
interface Document extends Readable {
public function getContents();
}
Following are the reasons for using interfaces:
By implementing an interface, the object’s caller needs to care only about the object’s interface, not implementations of the object’s methods. Therefore you can change the implementations without affecting the caller of the interface.
An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
An interface enables you to model multiple inheritances because a class can implement more than one interface.
No comments:
Post a Comment