How to Create Abstract Class in PHP: Syntax and Example
In PHP, you create an abstract class using the
abstract class keyword followed by the class name. Abstract classes can have abstract methods declared with abstract keyword, which must be implemented by child classes.Syntax
An abstract class is declared with the abstract class keyword. Inside it, you can define abstract methods with the abstract keyword and no body. Child classes must implement these abstract methods.
- abstract class ClassName: Declares an abstract class.
- abstract function methodName();: Declares an abstract method without a body.
- Concrete methods can also be included with full implementation.
php
abstract class Vehicle { abstract public function startEngine(); public function honk() { echo "Beep beep!\n"; } }
Example
This example shows an abstract class Vehicle with an abstract method startEngine(). The child class Car implements the abstract method and uses the concrete method honk().
php
<?php abstract class Vehicle { abstract public function startEngine(); public function honk() { echo "Beep beep!\n"; } } class Car extends Vehicle { public function startEngine() { echo "Engine started!\n"; } } $myCar = new Car(); $myCar->startEngine(); $myCar->honk(); ?>
Output
Engine started!
Beep beep!
Common Pitfalls
Common mistakes when using abstract classes in PHP include:
- Trying to instantiate an abstract class directly, which causes an error.
- Not implementing all abstract methods in child classes, which causes a fatal error.
- Defining abstract methods with a body, which is not allowed.
Always ensure child classes implement all abstract methods and never create objects from abstract classes.
php
<?php // Wrong: Instantiating abstract class // $vehicle = new Vehicle(); // Fatal error // Wrong: Abstract method with body // abstract class Wrong { // abstract public function test(); // No body allowed // } // Right: Implementing abstract method class Bike extends Vehicle { public function startEngine() { echo "Bike engine started!\n"; } } ?>
Quick Reference
Remember these key points when working with abstract classes in PHP:
- Use
abstract class ClassNameto declare an abstract class. - Declare abstract methods with
abstract public function methodName();without a body. - Child classes must implement all abstract methods.
- You cannot create an instance of an abstract class directly.
- Abstract classes can have both abstract and concrete methods.
Key Takeaways
Use the
abstract class keyword to declare an abstract class in PHP.Abstract methods must be declared without a body and implemented by child classes.
You cannot instantiate an abstract class directly; only child classes can be instantiated.
Abstract classes can contain both abstract and concrete methods.
Always implement all abstract methods in child classes to avoid errors.