Lesson 4 of 7
Abstract Classes & the final Keyword
Abstract classes sit between concrete classes (fully implemented) and interfaces (no implementation). They define a partial implementation and enforce a contract for subclasses. The final keyword prevents a class from being subclassed or a method from being overridden - used to lock down critical behaviour.
Abstract Classes vs final
<?php
declare(strict_types=1);
// ── Abstract class - partial implementation + contract ──────────
abstract class Repository {
public function __construct(protected readonly PDO $pdo) {}
// Concrete - shared implementation all repositories use
protected function query(string $sql, array $params = []): array {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
protected function execute(string $sql, array $params = []): int {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->rowCount();
}
// Abstract - each subclass MUST implement these
abstract public function findById(int $id): ?array;
abstract public function findAll(): array;
abstract public function save(array $data): int;
abstract public function delete(int $id): bool;
}
// ── Concrete repository ────────────────────────────────────────
class PostRepository extends Repository {
public function findById(int $id): ?array {
$results = $this->query(
"SELECT * FROM posts WHERE id = :id LIMIT 1",
[":id" => $id]
);
return $results[0] ?? null;
}
public function findAll(): array {
return $this->query("SELECT * FROM posts ORDER BY created_at DESC");
}
public function findPublished(): array {
return $this->query(
"SELECT * FROM posts WHERE published = 1 ORDER BY published_at DESC"
);
}
public function save(array $data): int {
if (isset($data["id"])) {
$this->execute(
"UPDATE posts SET title=:title, content=:content WHERE id=:id",
$data
);
return $data["id"];
}
$this->execute(
"INSERT INTO posts (title, content, author_id, slug) VALUES (:title,:content,:author_id,:slug)",
$data
);
return (int) $this->pdo->lastInsertId();
}
public function delete(int $id): bool {
return $this->execute("DELETE FROM posts WHERE id = :id", [":id" => $id]) > 0;
}
}
// ── final class - cannot be extended ─────────────────────────
final class DatabaseConfig {
private function __construct( // private constructor + final = singleton-like
public readonly string $host,
public readonly string $dbName,
public readonly string $username,
private readonly string $password,
) {}
public static function fromEnvironment(): static {
return new static(
host: getenv("DB_HOST") ?: "localhost",
dbName: getenv("DB_NAME") ?: "blog",
username: getenv("DB_USER") ?: "root",
password: getenv("DB_PASSWORD") ?: "",
);
}
public function getDsn(): string {
return "mysql:host={$this->host};dbname={$this->dbName};charset=utf8mb4";
}
public function getPassword(): string { return $this->password; }
}
// ── final method - prevent override of critical behaviour ─────
class PaymentProcessor {
final public function processPayment(float $amount): bool {
// This validation + audit logic must not change in subclasses
if ($amount <= 0) throw new InvalidArgumentException("Amount must be positive.");
$this->logPaymentAttempt($amount);
return $this->charge($amount);
}
protected function charge(float $amount): bool { return true; }
private function logPaymentAttempt(float $amount): void { /* ... */ }
}Quick Quiz
Tip
Tip
Practice Abstract Classes the final Keyword in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Abstract Classes & the final Keyword
Practice Task
Note
Practice Task - (1) Write a working example of Abstract Classes the final Keyword from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Abstract Classes the final Keyword is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?