In PHP OOP, an interface is a contract that defines a set of methods that a class must implement. An interface is similar to an abstract class, but it cannot contain properties or method implementations. Interfaces are used to define a common behavior that can be implemented by multiple classes.
Here’s an example of an interface:
interface Vehicle {
public function start();
public function stop();
}
class Car implements Vehicle {
public function start() {
echo "The car is starting.<br>";
}
public function stop() {
echo "The car is stopping.<br>";
}
}
class Motorcycle implements Vehicle {
public function start() {
echo "The motorcycle is starting.<br>";
}
public function stop() {
echo "The motorcycle is stopping.<br>";
}
}
//$vehicle = new Vehicle(); // Error: Cannot instantiate interface Vehicle.
$car = new Car();
$motorcycle = new Motorcycle();
$car->start(); // Output: The car is starting.
$car->stop(); // Output: The car is stopping.
$motorcycle->start(); // Output: The motorcycle is starting.
$motorcycle->stop(); // Output: The motorcycle is stopping.
In this example, the Vehicle
interface defines two methods: start()
and stop()
. The Car
and Motorcycle
classes implement the Vehicle
interface, which means that they must implement the start()
and stop()
methods. The Car
class and Motorcycle
class each implement the methods in their own way.
We cannot create an object of the Vehicle
interface, because it is an interface:
//$vehicle = new Vehicle(); // Error: Cannot instantiate interface Vehicle.
We can create objects of the Car
and Motorcycle
classes, and call their start()
and stop()
methods:
$car = new Car();
$motorcycle = new Motorcycle();
$car->start(); // Output: The car is starting.
$car->stop(); // Output: The car is stopping.
$motorcycle->start(); // Output: The motorcycle is starting.
$motorcycle->stop(); // Output: The motorcycle is stopping.
In summary, interfaces in PHP OOP are contracts that define a set of methods that a class must implement. They are used to define a common behavior that can be implemented by multiple classes. An interface cannot contain properties or method implementations, and cannot be instantiated. Classes that implement an interface must implement all of the methods defined by the interface.