PHP Abstract Classes
In this page:
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
abstract class Shape {
abstract function area();
}
class Square extends Shape {
function area() {
return 16;
}
}
$sq = new Square();
echo $sq->area();
?>
Login to try C/C++/Java/PHP code in the editor
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
abstract class Shape {
abstract function area();
}
class Circle extends Shape {
function area() {
return 3.14 * 5 * 5;
}
}
$c = new Circle();
echo $c->area();
?>
Login to try C/C++/Java/PHP code in the editor
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
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();
?>
Login to try C/C++/Java/PHP code in the editor
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
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();
?>
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: