Abstract Class vs. Interface: When to Use Which
The distinction between abstract classes and interfaces often feels trivial until you actually start designing a system. At first glance, they appear interchangeable because both enforce a contract: a child class must implement specific methods to function correctly. However, the ability to provide default implementations in an abstract class fundamentally shifts how you approach inheritance hierarchies and polymorphism.
The Power of Default Implementations
The most immediate difference lies in what you can put inside the definition. In your example, the abstract class Foo declares abstract methods, which forces every child class like myObj to provide its own implementation. This is useful when you need a base behavior that varies entirely per subclass.
However, an abstract class can hold concrete, non-abstract methods. Imagine a scenario where you have a Logger abstraction. You might want every logger to implement logMessage(), but you also want the core logic for writing to a file or a database to be shared among them.
abstract class AbstractLogger {
// Shared state accessible by all children
protected string $basePath;
public function __construct(string $path) {
$this->basePath = $path;
}
// Concrete method with default implementation
public function close() {
// Common cleanup logic (e.g., flush buffer, close stream)
fclose($this->stream);
}
// Abstract method requiring child implementation
abstract public function logMessage(string $message): void;
}
If you attempt to define a close() method inside an interface, the language simply won't allow it. Interfaces are purely about defining what a class can do, not how it does it. This makes abstract classes ideal for modeling "is-a" relationships where the base object possesses state and shared behavior, while interfaces remain strictly for capability contracts.
Multiple Inheritance and Flexibility
The second major divergence is the cardinality of inheritance. A class can extend only one parent class in languages like PHP, Java, or C#. Conversely, a class can implement any number of interfaces.
Consider a PaymentProcessor that needs to handle both credit cards and wallets, but you also want it to be serializable for logging purposes.
interface Processable {
public function process(string $amount): bool;
}
interface Serializable {
public function serialize(): string;
}
class CreditCardPayment implements Processable, Serializable {
// Must implement both contracts
public function process(string $amount): bool { return true; }
public function serialize(): string { return json_encode($this); }
}
If you tried to merge these into a single abstract class, the CreditCardPayment class would be forced to extend that one class. If another part of your system needed a WalletPayment with different state but the same processing logic, you'd face diamond inheritance issues or have to duplicate code. Interfaces solve this by allowing CreditCardPayment and WalletPayment to coexist under the same Processable contract without interfering with each other's internal state management.
When to Choose Each
You should reach for an abstract class when:
- You need to share concrete method implementations across subclasses.
- The subclass needs access to protected or private properties from the parent.
- The hierarchy represents a strict "is-a" relationship (e.g.,
Dogis aAnimal).
You should reach for an interface when:
- You need to define a capability that is independent of implementation details.
- You anticipate needing to compose types rather than inherit from them (dependency injection).
- You require multiple inheritance capabilities for a specific class.
In modern PHP development, particularly within frameworks like Laravel, the trend leans heavily toward interfaces for defining contracts between services (like Repository or Contract). This allows you to swap database engines or cache drivers without altering the core application logic. Abstract classes remain vital when building complex domain models where shared state and default behavior reduce boilerplate in your child classes.
If you find yourself struggling with these distinctions in a Laravel project, resources like https://laravelcompany.com often provide deeper dives into architectural patterns that leverage these language features effectively.