PHP Tutorial Tutorials - PHP OOP Polymorphism

PHP OOP Polymorphism

The term "Polymorphic" literally means "of multiple shapes" and in OOP, it means "having multiple behaviors".

In OOP,the polymorphisms can be achieved by using method overloading, operator overloading, and method overriding,
In PHP, Inheritance is one means of achieving polymorphism by using method overriding.

Take a look at a sketch of geometric figures implementation. They reuse a common interface for drawing and resizing:

One piece of code (polymorphic method) works with all shape objects. It results in different actions depending on the object being referenced.

function doSomething($shape){
    $shape->resize();
    $shape->draw();
}
$t = new Triangle();
$c = new Circle();
$r = new Rectangle();

doSomething($t);
doSomething($c);
doSomething($r);

With polymorphism,binding of a method to a n object is determined at run-time. It's also known as Run Time polymorphism, late binding, run-time binding or dynamic binding.

Full Code:

<?php
class Shape {
    public function resize() {  }
    public function draw() {    }
}

class Triangle extends Shape {
    public function resize() {
        echo "resize Triangle\n";
    }
    public function draw() {
        echo "draw Triangle\n";
    }
}
class Circle extends Shape {
    public function resize() {
        echo "resize Circle\n";
    }
    public function draw() {
        echo "draw Circle\n";
    }
}
class Rectangle extends Shape {
    public function resize() {
        echo "resize Rectangle\n";
    }
    public function draw() {
        echo "draw Rectangle\n";
    }
}

function doSomething($shape){
    $shape->resize();
    $shape->draw();
}
$t = new Triangle();
$c = new Circle();
$r = new Rectangle();

doSomething($t);
doSomething($c);
doSomething($r);
?>
Date:2019-10-09 01:00:06 From:www.Lautturi.com author:Lautturi