How to work with interfaces
How to create an interface
The syntax
interface interfaceName {
const constantName = constantValue;
public function methodName( parameterList );
}
An interface to show an object
interface Showable {
public function show();
}
An interface to require two test methods
interface Testable {
public function test1($value1);
public function test2($value1, $value2); }
An interface that provides three constants
interface EyeColor {
const GREEN = 1;
const BLUE = 2;
const BROWN = 3;
}
A class that inherits a class and implements an interface
class Employee extends Person implements Showable {
// The constructor and the get and set methods are the same as the Person class
Implement the Showable interface
public function show() {
echo("First Name:" . $this->getFirstName() . "<br />");
echo("Last Name: " . $this->getLastName() . "<br />");
echo("SSN: " . $this->ssn . "<br />");
echo 'Hire Date: ' . $this->hireDate . '"<br />");
}
}
A class declaration that implements three interfaces
class Customer extends Person implements Showable, Testable, EyeColor {
// class code here
}
Description
- An interface defines a set of public methods that can be implemented by a class. The interface doesn’t provide any code to implement the methods, but it provides the method names and parameter lists.
- All methods in an interface must be public and cannot be static.
- A class that implements an interface must provide an implementation for each method defined by the interface.
- An interface can define class constants that are available to any class that imple-ments the interface.
- Although a class can only inherit one class, it can implement multiple interfaces.
Back