php之PHP7支持多态吗

haluo1 阅读:88 2025-01-19 22:14:33 评论:0

我一直在使用 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
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号