In the programming world, one of the concepts that might be less known is interfaces. Interfaces help us define a common contract between classes without specifying their implementation details. In simple terms, an interface specifies what methods should exist within a class.
So, why should we use interfaces? First, these interfaces allow our code to be more extensible. Since we can have different classes that all implement a common shared interface, each class can have its specific details.
For example, let's assume we have an online store with several types of user accounts like customer, manager, and supplier. Each of these may have its specific methods, but they should all have a shared method for making purchases. Here, we can use an interface to define that shared method.
With the help of these interfaces, we can ensure that all our classes conform to a unified shape, allowing us to prevent mistakes resulting from inconsistent implementation.
Example Code in PHP
interface Buyable {
public function buy();
}
class Customer implements Buyable {
public function buy() {
echo "Customer is buying something";
}
}
class Admin implements Buyable {
public function buy() {
echo "Admin can manage the purchases";
}
}
Line-by-Line Explanation of the Code
interface Buyable
: Here we have a defined interface named Buyable
that only specifies one method buy
.
public function buy()
: This is a method defined that all classes implementing this interface must have.
class Customer implements Buyable
: The class Customer
is implementing the interface Buyable
and must, therefore, implement the buy
method.
class Admin implements Buyable
: The class Admin
must also implement the buy
method, but in its own way.