Pengiraan sfera
Buat fail Sphere.class.php baharu:
Anda perlu memberi perhatian di sini, kerana hanya terdapat kaedah luas dan perimeter dalam kelas grafik abstrak, dan sfera memerlukan luas dan kelantangan
Kami juga boleh melaksanakan kedua-dua ini kaedah, cuma Walau bagaimanapun, sudah cukup untuk mengira keluasan dan kelantangan semasa mengira, dan hanya menukarnya semasa mencetak
<?php function area() { return 4*pi()* $this->r* $this->r; ; } //求的体积 function zhou() { return pow((4/3)*$this->r*pi(),3); }
Kod keseluruhan adalah seperti berikut:
<?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; } }
Ubah suai kod 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 "请选择一个图形"; }
Jalankan paparan hasil: