Abstract vs Interface
Use an interface when unrelated classes share a contract. Use an abstract class when related classes share common implementation. PHP classes can implement multiple interfaces but extend only one abstract class.
Use an interface when unrelated classes share a contract. Use an abstract class when related classes share common implementation. PHP classes can implement multiple interfaces but extend only one abstract class.
<?php
// Interface: defines WHAT, not HOW
interface Payable {
public function charge(float $amount): bool;
}
// Abstract class: defines WHAT + some HOW
abstract class BasePayment implements Payable {
protected string $currency = "USD";
// Shared implementation
public function formatAmount(float $amount): string {
return number_format($amount, 2) . " " . $this->currency;
}
// Still requires implementation
abstract public function charge(float $amount): bool;
}
class StripePayment extends BasePayment {
public function charge(float $amount): bool {
echo "Charging " . $this->formatAmount($amount) . " via Stripe";
return true;
}
}
When in doubt: prefer interface (more flexible). Use abstract class only when you have reusable implementation to share.