Advertisement
Google Ad Slot: content-top
PHP OOP - Interfaces
PHP - What are Interfaces?
An interface in PHP defines a contract that classes must follow. Any class that implements an interface must define all its methods.
Key Characteristics of Interfaces
✅ Defined using the interface keyword.
✅ Cannot have properties (only method declarations).
✅ All methods are public by default.
✅ A class can implement multiple interfaces (unlike abstract classes).
✅ Interface methods cannot have implementations (must be defined in the implementing class).
Syntax
<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>
PHP - Interfaces vs. Abstract Classes
Both interfaces and abstract classes are used to define blueprints for other classes, but they have key differences in structure, usage, and flexibility.
Feature |
Interface |
Untitle |
|---|---|---|
Definition |
Uses |
Uses |
Method Implementation |
Cannot have method implementations (only method declarations) |
Can have both abstract (no implementation) and concrete (implemented) methods |
Properties (Variables) |
Cannot have properties |
Can have properties |
Method Access Modifiers |
Always |
Can be |
Constructors |
Cannot have constructors |
Can have constructors |
Multiple Inheritance |
A class can implement multiple interfaces |
A class can extend only one abstract class |
Use Case |
Used when multiple unrelated classes need to implement the same behavior |
Used for common functionality among related classes |
From the example above, let's say that we would like to write software which manages a group of animals. There are actions that all of the animals can do, but each animal does it in its own way.
Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently:
Explanation
1. Define an Interface (Animal)
- The
Animalinterface declares themakeSound()method. - Any class that implements
Animalmust definemakeSound().
2. Implementing Classes (Cat, Dog, Mouse)
- Each animal implements
Animaland definesmakeSound()differently.
3. Polymorphism: Handling Different Animals in a Loop
- We store different objects in an array.
- The loop calls
makeSound()on each object, without needing to check its type. - This is an example of polymorphism—different objects respond differently to the same method.