SyntaxStudy
Sign Up
PHP Abstract Classes vs Interfaces
PHP Intermediate 6 min read

Abstract Classes vs Interfaces

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.

Example
<?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;
    }
}
Pro Tip

When in doubt: prefer interface (more flexible). Use abstract class only when you have reusable implementation to share.