Sphere calculations
Create a new Sphere.class.php file:
You need to pay attention here, because the abstract graphics class only has area and perimeter methods, and the sphere requires area and volume
We can also implement these two methods, but the area and volume are calculated when calculating, and we can also change it when printing
<?php function area() { return 4*pi()* $this->r* $this->r; ; } //求的體積 function zhou() { return pow((4/3)*$this->r*pi(),3); }
The overall code is as follows:
<?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 .= "請(qǐng)輸入".$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 .= "半徑不是數(shù)字;"; $bz = false; } } return $bz; } }
Modify index .php code:
<?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."的周長(zhǎng)".$shape->zhou()."</b>"."<br>"; echo "<br>"; echo "<b>".$shape->name."的面積".$shape->area()."</b>"."<br>"; }else { echo "<b>錯(cuò)誤:$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>錯(cuò)誤:$shape->error</b>"; } echo "</div>"; } } } else { echo "請(qǐng)選擇一個(gè)圖形"; }
Run result display: