Sobes.tech
Middle

What is polymorphism and how is it used in PHP programming?

sobes.tech AI

Answer from AI

Polymorphism is the ability to use the same interface for different data types. In PHP, it manifests in several forms:

  1. Inheritance (Subtype Polymorphism): Child classes can override parent class methods, providing their own implementation. When calling a method on a base type object, the method from the specific child class will actually be executed, depending on the object type.

    <?php
    
    class Animal {
        public function makeSound() {
            echo "Generic animal sound\n";
        }
    }
    
    class Dog extends Animal {
        public function makeSound() {
            echo "Woof!\n";
        }
    }
    
    class Cat extends Animal {
        public function makeSound() {
            echo "Meow!\n";
        }
    }
    
    function makeAnimalSound(Animal $animal) {
        $animal->makeSound(); // Calls the method of the specific subtype
    }
    
    $dog = new Dog();
    $cat = new Cat();
    
    makeAnimalSound($dog); // Output: Woof!
    makeAnimalSound($cat); // Output: Meow!
    
  2. Interfaces (Interface Polymorphism): Different classes can implement the same interface, promising to provide a specific set of methods with the same signature. This allows working with objects of different classes through a unified interface.

    <?php
    
    interface Shape {
        public function getArea();
    }
    
    class Circle implements Shape {
        private $radius;
    
        public function __construct($radius) {
            $this->radius = $radius;
        }
    
        public function getArea() {
            return pi() * $this->radius * $this->radius;
        }
    }
    
    class Square implements Shape {
        private $side;
    
        public function __construct($side) {
            $this->side = $side;
        }
    
        public function getArea() {
            return $this->side * $this->side;
        }
    }
    
    function calculateTotalArea(array $shapes) {
        $totalArea = 0;
        foreach ($shapes as $shape) {
            if ($shape instanceof Shape) { // Check for interface compliance
                $totalArea += $shape->getArea();
            }
        }
        return $totalArea;
    }
    
    $shapes = [new Circle(5), new Square(4)];
    echo calculateTotalArea($shapes); // Outputs the sum of the areas of the circle and square
    
  3. Abstract Classes (Abstract Class Polymorphism): Similar to interface-based polymorphism but allows defining a base implementation for some methods.

Polymorphism increases flexibility, extensibility, and maintainability of code, enabling the writing of generic algorithms that work with collections of objects of different types through a single interface.

What is polymorphism and how is it used in PHP… - sobes.tech