Sobes.tech
Middle

How is polymorphism implemented in PHP?

sobes.tech AI

Answer from AI

Polymorphism in PHP is implemented through:

  1. Class inheritance: Child classes can override parent class methods.
  2. Interfaces: Classes implementing the same interface must have certain methods, but their implementation can differ.
  3. Traits: Methods from different traits used in a class can perform similar tasks but have different internal logic.

Example of polymorphism through inheritance:

<?php
class Animal {
    public function sound() {
        return "Unknown sound";
    }
}

class Dog extends Animal {
    public function sound() {
        return "Woof!"; // Override method
    }
}

class Cat extends Animal {
    public function sound() {
        return "Meow!"; // Override method
    }
}

function makeAnimalSound(Animal $animal) {
    echo $animal->sound() . "\n";
}

$dog = new Dog();
$cat = new Cat();

makeAnimalSound($dog); // Outputs "Woof!"
makeAnimalSound($cat); // Outputs "Meow!"

Example of polymorphism through interfaces:

<?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 printArea(Shape $shape) {
    echo "Area: " . $shape->getArea() . "\n";
}

$circle = new Circle(5);
$square = new Square(4);

printArea($circle); // Outputs the area of the circle
printArea($square); // Outputs the area of the square
How is polymorphism implemented in PHP? — PHP - sobes.tech