新建Sphere.class.php文件:
这里需要注意一下,因为抽象图形类里只有面积和周长的方法,而球体要求的是面积和体积
我们可以也是实现这两个方法,只不过计算时计算的是面积和体积就行,打印时也改一下就行了
<?php function area() { return 4*pi()* $this->r* $this->r; ; } //求的体积 function zhou() { return pow((4/3)*$this->r*pi(),3); }
整体代码如下:
<?php class Sphere extends Shape { private $r; // private $height; function __construct($arr = array()) { if (!empty($arr)) { $this->r = $arr['r']; // $this->height = $arr['height']; } $this->name = "球体"; $this->error = ''; } //:4π(R的平方),体积 4/3π*r的立方 //球的面积 function area() { return 4*pi()* $this->r* $this->r; ; } //求的体积 function zhou() { return pow((4/3)*$this->r*pi(),3); } function view($arr) { $form=''; $form .= "<form action='index.php?action=sphere' method='post'>"; $form .= "请输入".$arr['name']."的半径:<input type='text' name='r' value='".$_POST['r']."'/><br>"; $form .= "<br>"; $form .= "<input type='submit' name='sub' value='提交'/> "; $form .= "<input type='reset' name='ret' value='重置'/>"; $form .= "</form>"; echo $form; } function yan($arr) { $bz = true; if ($arr['r']< 0) { $this->error .= "半径小于0;"; $bz = false; } else { if (!is_numeric($arr['r'])) { $this->error .= "半径不是数字;"; $bz = false; } } return $bz; } }
修改index.php 代码:
<?php if (!empty($_GET['action'])) { // echo "传送成功"; $classname = ucfirst($_GET['action']); $shape = new $classname($_POST); $shape->view($_POST); if (isset($_POST['sub'])) { echo "<div id='footer'>"; if($shape->name!='球体'){ if ($shape->yan($_POST)) { echo "<b>".$shape->name."的周长".$shape->zhou()."</b>"."<br>"; echo "<br>"; echo "<b>".$shape->name."的面积".$shape->area()."</b>"."<br>"; }else { echo "<b>错误:$shape->error</b>"; } echo "</div>"; }else{ if ($shape->yan($_POST)) { echo "<b>".$shape->name."的表面积".$shape->area()."</b>"."<br>"; echo "<br>"; echo "<b>".$shape->name."的体积".$shape->zhou()."</b>"."<br>"; }else { echo "<b>错误:$shape->error</b>"; } echo "</div>"; } } } else { echo "请选择一个图形"; }
运行结果展示:
下一节