SyntaxStudy
Sign Up
PHP Intermediate 6 min read

Abstract Classes in PHP

Abstract Classes

Abstract classes can contain both abstract methods (no body) and concrete methods (with implementation). Use them when some behavior is shared but other behavior must be customized.

Example
<?php
abstract class BaseRepository {
    // Concrete: shared implementation
    public function findOrFail(int $id): array {
        $result = $this->find($id);
        if ($result === null) {
            throw new RuntimeException("Record {$id} not found");
        }
        return $result;
    }

    // Abstract: subclasses must implement
    abstract public function find(int $id): ?array;
    abstract public function save(array $data): int;
    abstract public function delete(int $id): bool;
}

class UserRepository extends BaseRepository {
    public function find(int $id): ?array { /* DB query */ return null; }
    public function save(array $data): int { return 1; }
    public function delete(int $id): bool { return true; }
}
Pro Tip

Abstract classes are great for template method patterns — define the skeleton algorithm in the base class, fill in steps in subclasses.