定义一个形状,该形状包含面积计算公式和周长计算公式; 分别定义圆形,矩形,三角形,都继承于该形状,都进行具体的面积和周长计算;
时间: 2024-03-26 17:38:33 浏览: 17
可以使用面向对象的方式来实现这个需求,代码如下:
```php
// 定义一个形状类 Shape
class Shape {
// 面积计算公式
public function getArea() {
return 0;
}
// 周长计算公式
public function getPerimeter() {
return 0;
}
}
// 圆形类,继承自形状类
class Circle extends Shape {
private $radius; // 圆的半径
// 构造函数
public function __construct($radius) {
$this->radius = $radius;
}
// 面积计算公式
public function getArea() {
return pi() * pow($this->radius, 2);
}
// 周长计算公式
public function getPerimeter() {
return 2 * pi() * $this->radius;
}
}
// 矩形类,继承自形状类
class Rectangle extends Shape {
private $width; // 矩形的宽
private $height; // 矩形的高
// 构造函数
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
// 面积计算公式
public function getArea() {
return $this->width * $this->height;
}
// 周长计算公式
public function getPerimeter() {
return 2 * ($this->width + $this->height);
}
}
// 三角形类,继承自形状类
class Triangle extends Shape {
private $a; // 三角形的边长a
private $b; // 三角形的边长b
private $c; // 三角形的边长c
// 构造函数
public function __construct($a, $b, $c) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
// 面积计算公式
public function getArea() {
$p = ($this->a + $this->b + $this->c) / 2;
return sqrt($p * ($p - $this->a) * ($p - $this->b) * ($p - $this->c));
}
// 周长计算公式
public function getPerimeter() {
return $this->a + $this->b + $this->c;
}
}
// 使用示例
$circle = new Circle(10);
echo "圆形的面积为:" . $circle->getArea() . "\n";
echo "圆形的周长为:" . $circle->getPerimeter() . "\n";
$rectangle = new Rectangle(5, 10);
echo "矩形的面积为:" . $rectangle->getArea() . "\n";
echo "矩形的周长为:" . $rectangle->getPerimeter() . "\n";
$triangle = new Triangle(3, 4, 5);
echo "三角形的面积为:" . $triangle->getArea() . "\n";
echo "三角形的周长为:" . $triangle->getPerimeter() . "\n";
```
输出结果为:
```
圆形的面积为:314.15926535898
圆形的周长为:62.831853071796
矩形的面积为:50
矩形的周长为:30
三角形的面积为:6
三角形的周长为:12
```