Interview frequency: …
Short answer
Choose an Interface to define an abstract behavioral contract for unrelated classes, and an Abstract Class to share code and implementation among classes in the same hierarchy.
Explanation
PHP lets a class implement multiple Interfaces (Multiple Interfaces), supporting Interface Segregation. Abstract Classes use Single Inheritance and can define state and fully implemented methods while requiring derived classes to implement only abstract methods.
Code example
interface PaymentGateway {
public function charge(int $amount): bool;
}
abstract class BaseGateway implements PaymentGateway {
protected function logTransaction(int $amount): void {
// Shared code
}
}Common mistakes
- Creating an Abstract Class with no shared implementation when it should have been an Interface.
Follow-up questions
- What are Anonymous Classes, and when are they used in PHP?
- What are Readonly Classes in PHP 8.2, and how do they support immutable Value Objects?