php - PHP7支持多态吗?

标签 php php-7

我一直在使用 5.6,但它的动态类型确实存在局限性。我刚刚查看了 PHP7 的文档,最终看起来他们正在削减困扰旧版本的问题,而且他们现在似乎正在设计语言。

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

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

最佳答案

关于您关于函数参数类型提示的问题,答案是"is",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 是稳定的并且被许多公司用于生产。

关于php - PHP7支持多态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36882487/

相关文章:

php - 有没有办法在 PHP 中扩展特征?

php - 正在生成随机 <br>

php - 如何检测 AJAX 中的错误?

php - 标题标签中的 XSS 攻击

php - 我想检索类(class)模块的实例

php - 转换为字符串时 (string)$value 和 "$value"之间哪个更快

php - PHP 中 !empty($variable) 和 count($variable) 的 bool 结果总是相等吗?

php - 如何用PHP从word文档中提取文本内容?

php - 替换字符串但不替换包含该字符串的特定单词

PHPExcel ERR_INVALID_RESPONSE 与 PHP7.0