JamesBlandford
JamesBlandford

Reputation: 178

Does PHP7 support polymorphism?

I have been using 5.6, but there are real limitations to it being dynamically typed. I've just looked at the documentation for PHP7 and it finally looks like they are cutting the crud which plagued the older versions, and it seems they are actually designing the language now.

I see that it supports type hinting on parameters, does this mean we can actually have polymorphic functions?

One more question, tangentially related but is the current version of PHP7 a stable release?

Upvotes: 3

Views: 2400

Answers (1)

Nicodemuz
Nicodemuz

Reputation: 4104

Regarding your question about type hinting on function parameters, the answer is a "Yes", PHP supports polymorphism in this regard.

We can take the typical shape example with rectangles and triangles. Lets first define these three classes:

Shape class

class Shape {
    public function getName()
    {
        return "Shape";
    }

    public function getArea()
    {
        // To be overridden
    }
}

Rectangle class

class Rectangle extends Shape {

    private $width;
    private $length;

    public function __construct(float $width, float $length)
    {
        $this->width = $width;
        $this->length = $length;
    }

    public function getName()
    {
        return "Rectangle";
    }


    public function getArea()
    {
        return $this->width * $this->length;
    }
}

Triangle class

class Triangle extends Shape {

    private $base;
    private $height;

    public function __construct(float $base, float $height)
    {
        $this->base = $base;
        $this->height = $height;
    }

    public function getName()
    {
        return "Triangle";
    }

    public function getArea()
    {
        return $this->base * $this->height * 0.5;
    }
}

Now we can write a function that takes the above Shape class.

function printArea(Shape $shape)
{
    echo "The area of `{$shape->getName()}` is {$shape->getArea()}" . PHP_EOL;
}

$shapes = [];
$shapes[] = new Rectangle(10.0, 10.0);
$shapes[] = new Triangle(10.0, 10.0);

foreach ($shapes as $shape) {
    printArea($shape);
}

An example run would produce the following results:

The area of `Rectangle` is 100
The area of `Triangle` is 50

Regarding your second question about PHP7 stability: Yes, PHP7 is stable and used in production by many companies.

Upvotes: 4

Related Questions