球體的計算
新建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 "请选择一个图形"; }
執行結果展示:
#