我一直在使用5.6版本,但它的动态类型存在实际限制。我刚查看了PHP7的文档,终于看起来他们正在削减困扰旧版本的垃圾,并且似乎他们现在正在设计语言。
我看到它支持参数类型提示,这是否意味着我们实际上可以拥有多态函数?
还有一个问题,与此相关的是,当前版本的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;
}
}
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非常稳定,并且已经被许多公司用于生产环境。