PHP Interfaces
Interfaces are a crucial part of object-oriented programming in PHP. They define a contract that any implementing class must follow, specifying methods that must be defined in the implementing class but without providing any implementation. Interfaces help enforce consistent behavior across multiple classes, promoting loose coupling and flexibility in the codebase. This article covers common interview questions and answers related to PHP interfaces.
What is an interface in PHP?
Answer:
An interface in PHP is a contract that defines a list of methods that a class must implement. Unlike a class, an interface contains only method declarations (without any implementation) and no properties. Any class that implements an interface must define all the methods declared in the interface.
Example:
interface Vehicle {
public function startEngine();
}
class Car implements Vehicle {
public function startEngine() {
echo "Car engine started.";
}
}
$car = new Car();
$car->startEngine(); // Outputs: Car engine started.How do you declare an interface in PHP?
Answer:
An interface is declared using the interface keyword, followed by the interface name and a list of method signatures without implementation.
Example:
interface Flyable {
public function fly();
}How do you implement an interface in a class in PHP?
Answer:
A class implements an interface using the implements keyword. The class must provide the implementation for all the methods declared in the interface.
Example:
interface Flyable {
public function fly();
}
class Airplane implements Flyable {
public function fly() {
echo "Airplane is flying.";
}
}
$plane = new Airplane();
$plane->fly(); // Outputs: Airplane is flying.What happens if a class does not implement all methods of an interface?
Answer:
If a class does not implement all the methods of an interface, PHP will throw a fatal error. Implementing an interface requires that every method defined in the interface is provided in the class, or the class must be declared as abstract.
Example:
interface Vehicle {
public function startEngine();
}
class Car implements Vehicle {
// Fatal error: Class Car contains 1 abstract method and must implement
// interface Vehicle (Car::startEngine)
}Can a class implement multiple interfaces in PHP?
Answer:
Yes, a class can implement multiple interfaces by separating the interface names with commas. The class must then provide implementations for all methods in all the interfaces.
Example:
interface Driveable {
public function drive();
}
interface Flyable {
public function fly();
}
class FlyingCar implements Driveable, Flyable {
public function drive() {
echo "Driving on the road.";
}
public function fly() {
echo "Flying in the sky.";
}
}
$car = new FlyingCar();
$car->drive(); // Outputs: Driving on the road.
$car->fly(); // Outputs: Flying in the sky.Can an interface extend another interface in PHP?
Answer:
Yes, an interface can extend one or more other interfaces. The child interface inherits all the methods from the parent interface, and any class that implements the child interface must implement all the methods from the parent and child interfaces.
Example:
interface Vehicle {
public function startEngine();
}
interface AdvancedVehicle extends Vehicle {
public function autoDrive();
}
class Tesla implements AdvancedVehicle {
public function startEngine() {
echo "Engine started.";
}
public function autoDrive() {
echo "Auto-driving enabled.";
}
}
$tesla = new Tesla();
$tesla->startEngine(); // Outputs: Engine started.
$tesla->autoDrive(); // Outputs: Auto-driving enabled.What is the difference between an interface and an abstract class in PHP?
Answer:
The key differences between an interface and an abstract class are:
- Methods:
- Interface: Can only declare method signatures. The implementing class must provide the method implementations.
- Abstract Class: Can have both abstract methods (method signatures) and concrete methods (methods with implementations).
- Properties:
- Interface: Cannot have properties.
- Abstract Class: Can have properties.
- Inheritance:
- Interface: A class can implement multiple interfaces.
- Abstract Class: A class can only extend one abstract class.
- Use Case:
- Interface: Used to define a contract or common behavior across unrelated classes.
- Abstract Class: Used when classes share common functionality and may have some common properties or method implementations.
Can an interface have constants in PHP?
Answer:
Yes, an interface can have constants. Constants declared in an interface must be public and cannot be changed. Any class implementing the interface can access these constants.
Example:
interface Vehicle {
const WHEELS = 4;
public function startEngine();
}
class Car implements Vehicle {
public function startEngine() {
echo "This car has " . self::WHEELS . " wheels.";
}
}
$car = new Car();
$car->startEngine(); // Outputs: This car has 4 wheels.Can you use access modifiers in interfaces in PHP?
Answer:
All methods in an interface must be public. PHP does not allow you to declare methods with other access modifiers (e.g., private, protected) in an interface. By default, all methods in an interface are public.
Example:
interface Vehicle {
// This is implicitly public
public function startEngine();
}How do you ensure a class adheres to multiple interfaces in PHP?
Answer:
To ensure a class adheres to multiple interfaces, the class must implement each of the interfaces by providing method implementations for all methods declared in each interface. Multiple interfaces are separated by commas in the implements clause.
Example:
interface Swimmable {
public function swim();
}
interface Flyable {
public function fly();
}
class Duck implements Swimmable, Flyable {
public function swim() {
echo "Duck is swimming.";
}
public function fly() {
echo "Duck is flying.";
}
}
$duck = new Duck();
$duck->swim(); // Outputs: Duck is swimming.
$duck->fly(); // Outputs: Duck is flying.Can a class implement an interface partially in PHP?
Answer:
No, a class cannot implement an interface partially. If a class implements an interface, it must implement all the methods declared in that interface. If a class does not implement all methods, it must be declared as abstract.
Example:
interface Vehicle {
public function startEngine();
}
abstract class Car implements Vehicle {
// Partially implemented, must be declared as abstract
}What is polymorphism in the context of PHP interfaces?
Answer:
Polymorphism refers to the ability of different classes to be treated as instances of the same interface, even though they may have different implementations. This allows for flexibility in programming, as the exact class being used does not need to be known ahead of time, as long as it implements the interface.
Example:
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
echo "Drawing a circle.";
}
}
class Square implements Shape {
public function draw() {
echo "Drawing a square.";
}
}
function renderShape(Shape $shape) {
$shape->draw();
}
$circle = new Circle();
$square = new Square();
renderShape($circle); // Outputs: Drawing a circle.
renderShape($square); // Outputs: Drawing a square.Can interfaces extend multiple interfaces in PHP?
Answer:
Yes, an interface can extend multiple interfaces in PHP. This allows the child interface to inherit all the methods from the parent interfaces. Any class implementing the child interface must implement all the methods from all the parent interfaces.
Example:
interface Vehicle {
public function startEngine();
}
interface Electric {
public function chargeBattery();
}
interface ElectricCar extends Vehicle, Electric {
}
class Tesla implements ElectricCar {
public function startEngine() {
echo "Starting electric engine.";
}
public function chargeBattery() {
echo "Charging battery.";
}
}
$tesla = new Tesla();
$tesla->startEngine(); // Outputs: Starting electric engine.
$tesla->chargeBattery(); // Outputs: Charging battery.Can interfaces be used for dependency injection in PHP?
Answer:
Yes, interfaces are commonly used in dependency injection. By injecting an object that implements an interface rather than a specific class, the code becomes more flexible and decoupled, allowing different implementations of the interface to be swapped easily.
Example:
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
echo "Logging to a file: $message";
}
}
class App {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
public function run() {
$this->logger->log("Application is running");
}
}
$logger = new FileLogger();
$app = new App($logger);
$app->run(); // Outputs: Logging to a file: Application is runningWhat happens if two interfaces have methods with the same name and a class implements both interfaces?
Answer:
If two interfaces have methods with the same name and a class implements both interfaces, the class must provide a single implementation for that method. The method should satisfy both interfaces as long as the signatures match.
Example:
interface Printable {
public function printData();
}
interface Displayable {
public function printData(); // Same method name
}
class Report implements Printable, Displayable {
public function printData() {
echo "Printing and displaying data.";
}
}
$report = new Report();
$report->printData(); // Outputs: Printing and displaying data.