PHP定义一个计算图形面积抽象类,定义两个子类分别用于实现计算矩形和椭圆形的面积分别实例化两个子类的对象用于计算指定高与宽图形的面积。
代码如下
<meta charset="utf-8">
<?php
abstract class Shape{
public $width;
public $height;
abstract public function GetArea();
}
class Rectangle extends Shape{
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
function GetArea(){return $this->width * $this->height;}
}
class Ellipse extends Shape{
public function __construct( $width, $height ) {
$this->width = $width;
$this->height = $height;
}
function GetArea(){return round(pi()*$this->width * $this->height,2);}
}
$rect=new Rectangle(3,4);
echo "矩形面积:3x4=".$rect->GetArea().'<br>';
$ell=new Ellipse(3,4);
echo "椭圆面积:3x4=".$ell->GetArea().'<br>';
?>