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 .= "请输入".$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;
    }
}

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."的周长".$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 "请选择一个图形";
}

Run result display:

gif5新文件 (32).gif

Continuing Learning
||
<?php echo "球体的计算";
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!