How do Interfaces work in PHP?
Interfaces let you tell a class what methods it should have.
Interfaces make it easy for different classes to be used in the same way. \”Polymorphism\” means that more than one class can use the same interface.
The interface keyword is used to declare an interface:
Syntax
<?php
interface Interface_Name {
public function testMethod1();
public function testMethod2($one, $two);
public function testMethod3() : string;
}
?>
PHP: Abstract Classes vs. Interfaces
Interfaces are like abstract classes in a way. Interfaces and abstract classes are different in the following ways:
- Abstract classes can have properties, but interfaces can\’t. All interface methods have to be public, but abstract class methods can be either public or protected.
- All of the methods in an interface are abstract, so they can\’t be used in code, and you don\’t need to use the abstract keyword.
- Classes can implement an interface at the same time that they inherit from another class.
Using Interfaces in PHP
A class must use the implements keyword if it wants to use an interface.
When a class implements an interface, it must also implement all of the methods in the interface.
Example
<!DOCTYPE html>
<html>
<body><?php
interface Color {
public function showcolorname();
}class Red implements Color {
public function showcolorname() {
echo \”Red Color\”;
}
}$color = new Red();
$color->showcolorname();
?></body>
</html>
Output
Red Color