← Back to PHP Course | Chapter 8: OOP | Lesson 7 of 14

PHP Abstract Classes

What is an Abstract Class?

An abstract class, declared with the abstract keyword, cannot be instantiated directly with new — it exists only to be extended, serving as a partial template that defines shared structure for its subclasses.

Example: What is an Abstract Class?

php
<?php
abstract class Shape {
    abstract function area();
}
class Square extends Shape {
    function area() {
        return 16;
    }
}
$sq = new Square();
echo $sq->area();
?>

Defining Abstract Methods

abstract methods inside an abstract class have no body — just a signature — forcing every concrete (non-abstract) subclass to provide its own implementation, or PHP will raise a fatal error.

Example: Defining Abstract Methods

php
<?php
abstract class Shape {
    abstract function area();
}
class Circle extends Shape {
    function area() {
        return 3.14 * 5 * 5;
    }
}
$c = new Circle();
echo $c->area();
?>

Implementing Abstract Methods

Abstract classes can still contain regular, fully-implemented methods and properties alongside their abstract ones, letting you share common logic while requiring subclasses to fill in the parts that genuinely differ.

Example: Implementing Abstract Methods

php
<?php
abstract class Shape {
    function describe() {
        echo "This is a shape with area: ";
    }
    abstract function area();
}
class Square extends Shape {
    function area() {
        return 9;
    }
}
$sq = new Square();
$sq->describe();
echo $sq->area();
?>

Abstract Classes with Regular Methods

Use an abstract class when several related classes should share both common state/behavior and a mandatory contract for a few specific methods, unlike a plain interface, which can't hold shared implementation.

Example: Abstract Classes with Regular Methods

php
<?php
abstract class Employee {
    function clockIn() {
        echo "Clocked in\n";
    }
    abstract function calculatePay();
}
class Hourly extends Employee {
    function calculatePay() {
        return 15 * 40;
    }
}
$emp = new Hourly();
$emp->clockIn();
echo $emp->calculatePay();
?>

Parameter Matching Rules

A typical example is an abstract PaymentMethod class with a shared logTransaction() method plus an abstract processPayment() method, where CreditCard and PayPal subclasses each implement processPayment() their own way.

Example: Parameter Matching Rules

php
<?php
abstract class PaymentMethod {
    function logTransaction() {
        echo "Transaction logged\n";
    }
    abstract function processPayment();
}
class CreditCard extends PaymentMethod {
    function processPayment() {
        echo "Processing credit card payment";
    }
}
$payment = new CreditCard();
$payment->logTransaction();
$payment->processPayment();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.