In PHP, an abstract class is a class that cannot be instantiated on its own and serves as a blueprint for other classes. Abstract classes are used when you want to define a common structure or behavior that should be shared among multiple subclasses. Abstract classes can contain both regular methods with implementations and abstract methods without implementations, which must be defined by any concrete subclasses.
Here's how you can define and use abstract classes in PHP:
Defining an Abstract Class:
You define an abstract class using the `abstract` keyword before the `class` keyword. Abstract classes can have regular methods with implementations and abstract methods without implementations.
php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function calculateArea();
}
In this example, `Shape` is an abstract class with a constructor and an abstract method `calculateArea()`. Concrete subclasses of `Shape` must implement the `calculateArea()` method.
Creating Subclasses:
Subclasses that inherit from an abstract class must implement all its abstract methods. They can also override and provide their own implementations for the regular methods.
php
class Circle extends Shape {
protected $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function calculateArea() {
return 3.14159 * $this->radius * $this->radius;
}
}
class Rectangle extends Shape {
protected $width;
protected $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}
Using Subclasses:
You can create instances of the subclasses and call methods as usual.
php
$circle = new Circle("Red", 5);
$rectangle = new Rectangle("Blue", 4, 6);
echo "Circle area: " . $circle->calculateArea(); // Output: Circle area: 78.53975
echo "Rectangle area: " . $rectangle->calculateArea(); // Output: Rectangle area: 24
Note: Abstract classes cannot be directly instantiated. They are meant to be extended by concrete subclasses that provide implementations for all abstract methods.
Abstract classes are useful when you want to create a shared structure among related classes while enforcing certain methods to be implemented by the subclasses. They provide a level of abstraction and help in achieving more organized and modular code.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc