How can abstract classes in PHP help in avoiding the need to implement functions in every derived class?
When we have a common set of methods that need to be implemented in multiple classes, we can use abstract classes in PHP to define these methods without providing an implementation. This way, we can avoid the need to implement the same functions in every derived class, saving time and reducing code duplication.
<?php
abstract class Shape {
abstract public function calculateArea();
abstract public function calculatePerimeter();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
public function calculatePerimeter() {
return 2 * pi() * $this->radius;
}
}
class Square extends Shape {
private $sideLength;
public function __construct($sideLength) {
$this->sideLength = $sideLength;
}
public function calculateArea() {
return pow($this->sideLength, 2);
}
public function calculatePerimeter() {
return 4 * $this->sideLength;
}
}
$circle = new Circle(5);
echo "Circle Area: " . $circle->calculateArea() . "\n";
echo "Circle Perimeter: " . $circle->calculatePerimeter() . "\n";
$square = new Square(4);
echo "Square Area: " . $square->calculateArea() . "\n";
echo "Square Perimeter: " . $square->calculatePerimeter() . "\n";
?>
Related Questions
- What potential security risks are associated with using the "LIKE" operator in a SQL query for username validation in PHP?
- What potential issues can arise from relying on IDs for counting registered users in a database?
- In what situations would it be advisable to use a recursive function or loop in PHP to adjust a calculated date based on weekends and holidays, rather than relying solely on built-in functions like strtotime?