Defining abstract classes
Learn to define an incomplete class template with abstract class.
Abstract classes as templates
Sometimes you want a class to act as a starting template but not be used on its own. For example, every shape computes an area; but a generic 'shape' is not meaningful alone.
In PHP you use abstract class for this. The declaration is abstract class Shape. An abstract class cannot be instantiated with new; it only provides a skeleton for subclasses to inherit.
It can contain regular properties and methods. So an abstract class is an incomplete draft; concrete classes complete it.
Abstract class declaration and example
To declare an abstract class, put the abstract keyword in front of class: abstract class Shape. You can add regular methods and properties inside; they pass to subclasses as-is.
Below, the describe() method of the Shape abstract class is a regular method. The Circle class inherits and uses it:
abstract class Shape {
public function describe(): string {
return "A shape";
}
}
class Circle extends Shape {}
$c = new Circle();
echo $c->describe();Note: new Shape() causes a PHP error; but new Circle() is valid.
Exercise Abstract class and concrete subclass
Define a Shape abstract class. Inside it, add a public function describe(): string method that does return "A shape";. Then derive a Circle class from Shape with extends (an empty body is enough). Create an instance with $c = new Circle() and print echo $c->describe() . "\n".
Show example solution
Write abstract class Shape { ... } with a describe() method inside. Derive Circle with extends Shape. Create the instance with new Circle().
Example solution:
<?php
// Define the Shape abstract class
abstract class Shape {
public function describe(): string {
return "A shape";
}
}
class Circle extends Shape {
}
$c = new Circle();
echo $c->describe() . "\n";
Test yourself
-
Which statement about abstract classes is true?
- It can be instantiated directly with new
- It serves as a template for subclasses and cannot be instantiated with new
- It can only contain static methods
- It cannot contain properties
Show answer
It serves as a template for subclasses and cannot be instantiated with new — Correct. An abstract class is a template; it cannot be instantiated with new, only inherited with extends.
-
Abstract class declaration
____ Shape { public function describe(): string { return "A shape"; } }Show answer
abstract class Shape { public function describe(): string { return "A shape"; } } -
Match the abstract class concepts
- abstract class
- Template class
- new Shape()
- Causes an error
- extends Shape
- Subclass declaration
- Regular methods inside
- Allowed