Skip to content
PHP Logo

Are there best practices for optimizing PHP code to reduce the need for extensive conditional statements?

One way to optimize PHP code and reduce the need for extensive conditional statements is by using polymorphism. By creating classes that implement a common interface or extend a base class, you can achieve the desired behavior without the need for complex if-else or switch-case blocks.

php
interface Shape {
    public function calculateArea();
}

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

class Square implements Shape {
    private $sideLength;

    public function __construct($sideLength) {
        $this->sideLength = $sideLength;
    }

    public function calculateArea() {
        return pow($this->sideLength, 2);
    }
}

$circle = new Circle(5);
echo $circle->calculateArea(); // Output: 78.54

$square = new Square(4);
echo $square->calculateArea(); // Output: 16