How can abstract classes be effectively used to encapsulate functions and variables in PHP?
Abstract classes in PHP can be effectively used to encapsulate functions and variables by defining a blueprint for other classes to inherit from. This allows for creating a structure where common functionality can be shared among multiple classes while enforcing specific methods to be implemented by the child classes. By declaring methods as abstract in the abstract class, child classes are required to implement those methods, ensuring consistency and enforcing a contract for how the class should be used.
<?php
// Abstract class defining a blueprint for other classes to inherit from
abstract class Shape {
protected $name;
public function __construct($name) {
$this->name = $name;
}
// Abstract method that must be implemented by child classes
abstract public function calculateArea();
}
// Child class implementing the abstract class
class Circle extends Shape {
private $radius;
public function __construct($name, $radius) {
parent::__construct($name);
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
// Create an instance of the Circle class
$circle = new Circle('Circle', 5);
echo 'Area of ' . $circle->name . ': ' . $circle->calculateArea();
?>