In what scenarios would using an abstract class be more beneficial than an interface in PHP?
Abstract classes in PHP can be more beneficial than interfaces when you want to provide a partial implementation of a class along with some abstract methods that must be implemented by the child classes. Abstract classes can contain both abstract and non-abstract methods, allowing for code reusability and providing a structure for related classes to follow.
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
// Abstract method that must be implemented by child classes
abstract public function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
$circle = new Circle('red', 5);
echo $circle->calculateArea(); // Output: 78.539816339745
?>