Junior
What is polymorphism?
sobes.tech AI
Answer from AI
Polymorphism is the ability to work with different types of objects using a single interface. In the context of OOP in PHP, this manifests through:
- Inheritance: Child classes can override methods of the parent class, providing their own implementation. When this method is called on a child class object, its specific version will be executed.
- Interfaces: Different classes can implement the same interface, providing specific implementations of the methods defined in the interface. Objects of these classes can be considered as objects of the interface type, calling interface methods on them.
Polymorphism allows creating more flexible and extensible code, as you can work with a collection of objects of different types uniformly, without knowing the specific type of each object in advance.
Example with inheritance:
<?php
class Animal {
public function makeSound() {
// Base implementation
}
}
class Dog extends Animal {
public function makeSound() {
return "Woof!";
}
}
class Cat extends Animal {
public function makeSound() {
return "Meow!";
}
}
// Working with objects of different classes through a common interface (makeSound method)
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
echo $animal->makeSound() . "\n";
}
Example with 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() * pow($this->radius, 2);
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function getArea() {
return pow($this->side, 2);
}
}
// Working with objects of different classes through a common interface Shape
$shapes = [new Circle(5), new Square(10)];
foreach ($shapes as $shape) {
echo "Area: " . $shape->getArea() . "\n";
}