面向对象的实例应用:图形计算器

1.使用动态页面实现图形计算器,可以计算给定图形的周长和面积
2.可以使用接口或抽象类作为规范,再写各子类的多态
3.动态页面如下:



    
        
        
        
    
    
        

图形计算器

矩形|| 三角形|| 圆形
input(); if(!empty($_POST)){ if($s->identify($_POST)){ echo $s->name."的周长为:".$s->getPerimeter()."
"; echo $s->name."的面积为:".$s->getArea()."
"; } } }else{ echo "请选择图形!
"; } ?>

4.接口与各子类如下:

line1=$arr['line1'];
                $this->line2=$arr['line2'];
                $this->line3=$arr['line3'];
                $this->name="三角形";
            }    
        }        
        function input(){
            if(!empty($_POST)){
                $line1=$_POST['line1'];
                $line2=$_POST['line2'];
                $line3=$_POST['line3'];
            }else{
                $line1=null;
                $line2=null;
                $line3=null;
            }
            $form="
"; $form.="
"; $form.="
"; $form.="
"; $form.="
"; $form.="
"; echo $form; } function getPerimeter(){ return $this->line1+$this->line2+$this->line3; } function getArea(){ $p=$this->getPerimeter()/2; return sqrt($p*($p-$this->line1)*($p-$this->line2)*($p-$this->line3)); } function identify($arr){ $line1=$arr['line1']; $line2=$arr['line2']; $line3=$arr['line3']; $identifier=true; if($line1<0){ echo "第一条边小于0
"; $identifier=false; } if($line2<0){ echo "第二条边小于0
"; $identifier=false; } if($line3<0){ echo "第三条边小于0
"; $identifier=false; } if(($line1+$line2<$line3)||($line1+$line3<$line2)||($line2+$line3<$line1)){ $identifier=false; echo "两边之和小于第三边
"; } return $identifier; } } class Cycle implements Calculate { private $radius; public $name; function __construct($arr){ if(!empty($arr)){ $this->radius=$arr['radius']; $this->name="圆形"; } } function input(){ $form="
"; $form.="
"; $form.="
"; $form.="
"; echo $form; } function getPerimeter(){ return 2*pi()*$this->radius; } function getArea(){ return pi()*$this->radius*$this->radius; } function identify($arr){ $identifier=true; if($arr['radius']<0){ echo "半径不能小于0!
"; $identifier=false; } return $identifier; } } class Rect implements Calculate { private $height; private $width; public $name; function __construct($arr){ if(!empty($arr)){ $this->width=$arr['width']; $this->height=$arr['height']; $this->name="矩形"; } } function input(){ $form="
"; $form.="
"; $form.="
"; $form.="
"; $form.="
"; echo $form; } function getPerimeter(){ return 2*($this->width+$this->height); } function getArea(){ return $this->width*$this->height; } function identify($arr){ $identifier=true; if($arr['width']<0){ echo "宽度不能小于0!
"; $identifier=false; } if($arr['height']<0){ echo "高度不能小于0!
"; $identifier=false; } return $identifier; } } ?>

你可能感兴趣的:(php)