PHP7 是否支持多态性?


Does PHP7 support polymorphism?

我一直在使用 5.6,但它动态类型存在真正的限制。我刚刚看了 PHP7 的文档,最后看起来他们正在削减困扰旧版本的粗制滥造,而且看起来他们现在实际上正在设计语言。

我看到它支持参数的类型提示,这是否意味着我们实际上可以拥有多态函数?

还有一个问题,切线相关,但当前版本的 PHP7 是稳定版本吗?

关于你关于函数参数类型提示的问题,答案是"是",PHP 在这方面支持多态性。

我们可以以矩形和三角形的典型形状为例。让我们首先定义这三个类:

形状类

class Shape {
    public function getName()
    {
        return "Shape";
    }
    public function getArea()
    {
        // To be overridden
    }
}

矩形类

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;
    }
}

三角形类

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;
    }
}

现在我们可以编写一个采用上述 Shape 类的函数。

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);
}

示例运行将产生以下结果:

The area of `Rectangle` is 100
The area of `Triangle` is 50
关于你关于 PHP7

稳定性的第二个问题:是的,PHP7 是稳定的,被许多公司用于生产。