How can the concept of polymorphism be affected by the use of static methods in PHP, and what are the best practices to avoid such issues?
When using static methods in PHP, polymorphism can be affected because static methods are bound to the class they are defined in and not to the object's type. To avoid this issue, it's best to use instance methods and rely on inheritance and interfaces to achieve polymorphism.
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
public function calculateArea() {
// Calculate area for a circle
}
}
class Square implements Shape {
public function calculateArea() {
// Calculate area for a square
}
}
function printArea(Shape $shape) {
echo $shape->calculateArea();
}
$circle = new Circle();
printArea($circle);
$square = new Square();
printArea($square);
Related questions
-
PHP CSS hover effects
-
PHP classes inheritance
-
unlink PHP file deletion