Difference between abstract Class and Interface
In PHP, abstract classes and interfaces are both tools for achieving abstraction and defining a contract for classes, but they have some key differences. Here are the main distinctions between abstract classes and interfaces:
Abstract Class:
Example of an abstract class:
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
public function eat() {
echo "{$this->name} is eating.";
}
}
Interface:
Example of an interface:
interface Logger {
public function log($message);
}
Key Points:
Use an abstract class when you want to provide a common base class with some shared functionality and allow derived classes to override or extend it.
Use an interface when you want to define a contract that multiple classes can implement. This is especially useful when those classes may not share a common base implementation.
You can combine both abstract classes and interfaces. A class can extend an abstract class and implement one or more interfaces.
abstract class Animal {
// Abstract methods and shared functionality
}
interface Swimmer {
public function swim();
}
class Fish extends Animal implements Swimmer {
// Implement abstract methods and interface method
}
In summary, abstract classes provide a way to share code and define a base class, while interfaces provide a contract that classes can adhere to without providing any implementation details. The choice between them depends on the specific requirements of your design.
Thank you.