In PHP, an abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes and may contain abstract methods that must be implemented by its subclasses. Abstract classes are declared using the abstract keyword.
abstract class AbstractClass {
// Abstract method declaration
abstract public function abstractMethod();
// Regular method
public function regularMethod() {
// Code
}
}
Example of an Abstract Class:
Here's an example to illustrate how abstract classes work in PHP:
abstract class Shape {
protected $name;
public function __construct($name) {
$this->name = $name;
}
// Abstract method
abstract public function getArea();
}
class Circle extends Shape {
private $radius;
public function __construct($name, $radius) {
parent::__construct($name);
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($name, $width, $height) {
parent::__construct($name);
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
// Cannot instantiate an abstract class
// $shape = new Shape(); // Error: Cannot instantiate abstract class Shape
// Creating objects of the concrete classes
$circle = new Circle("Circle", 5);
$rectangle = new Rectangle("Rectangle", 4, 6);
// Calling getArea() on the objects
echo "Area of {$circle->name}: {$circle->getArea()}<br>"; // Output: Area of Circle: 78.53975
echo "Area of {$rectangle->name}: {$rectangle->getArea()}<br>"; // Output: Area of Rectangle: 24
In this example:
Abstract classes in PHP are classes that cannot be instantiated and are used as a blueprint for other classes. They can contain both abstract and non-abstract methods, but they must be extended by concrete subclasses that provide implementations for the abstract methods. Abstract classes are useful for defining a common interface and behavior that subclasses must adhere to.