How can you effectively use polymorphism in PHP to enhance class functionality without multiple inheritance?
In PHP, you can effectively use polymorphism to enhance class functionality without multiple inheritance by utilizing interfaces and abstract classes. By defining common methods in interfaces and abstract classes, you can ensure that different classes implement these methods in their own unique way, allowing for polymorphic behavior without the need for multiple inheritance.
<?php
// Define an interface with common methods
interface Shape {
public function calculateArea();
}
// Create abstract class with some common functionality
abstract class AbstractShape implements Shape {
public function printArea() {
echo "The area is: " . $this->calculateArea();
}
}
// Implement different shapes
class Circle extends AbstractShape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
class Square extends AbstractShape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return pow($this->side, 2);
}
}
// Usage
$circle = new Circle(5);
$circle->printArea(); // Output: The area is: 78.539816339745
$square = new Square(4);
$square->printArea(); // Output: The area is: 16
Related Questions
- How can .htaccess files be used to override PHP settings and restrictions for file uploads in a web application?
- How can developers ensure the security of their PHP code when handling user input and database queries?
- How can PHP limits be utilized to manage memory usage when dealing with large datasets?