这篇文章主要介绍了PHP实现的简单三角形、矩形周长面积计算器分享,本文的实现相对较简单,同时提供了代码文件下载,需要的朋友可以参考下
运用PHP面向对象的知识设计一个图形计算器,同时也运用到了抽象类知识,这个计算器可以计算三角形的周长和面积以及矩形的周长和面积。本图形计算器有4个页面:1.PHP图形计算器主页index.php; 2.形状的抽象类shape.class.php; 3三角形计算类triangle.class.php; 4.矩形计算类rect.class.php。
PHP图形计算器代码点击下载: php图形计算器.zip
代码分别如下:
PHP图形计算器主页:
<title>简单的图形计算器</title> <h1>简单的图形计算器</h1> 矩形 || 三角形 <hr><br> view(); //第三步:用户是否提交了对应图形界面的表单 if(isset($_POST['dosubmit'])) { //第四步:查看用户输出的数据是否正确, 失败则提示 if($shape->yan($_POST)) { //计算图形的周长和面积 echo $shape->name."的周长为:".$shape->zhou()."<br>"; echo $shape->name."的面积为:".$shape->area()."<br>"; } } //如果用户没有单击链接, 则是默认访问这个主程序 }else { echo "请选择一个要计算的图形!<br>"; } ?>
形状的抽象类:
abstract class Shape{ //形状的名称 public $name; //形状的计算面积方法 abstract function area(); //形状的计算周长的方法 abstract function zhou(); //形状的图形表单界面 abstract function view(); //形状的验证方法 abstract function yan($arr); }
三角形计算类文件:
class Triangle extends Shape { private $bian1; private $bian2; private $bian3; function __construct($arr = array()) { if(!empty($arr)) { <span style="color:transparent">来源gaodai#ma#com搞*代#码网</span> $this->bian1 = $arr['bian1']; $this->bian2 = $arr['bian2']; $this->bian3 = $arr['bian3']; } $this->name = "三角形"; } function area() { $p = ($this->bian1 + $this->bian2 + $this->bian3)/2; return sqrt($p*($p-$this->bian1)*($p-$this->bian2)*($p-$this->bian3)); } function zhou() { return $this->bian1 + $this->bian2 + $this->bian3; } function view() { $form = ''; $form .= $this->name.'第一个边:<br>'; $form .= $this->name.'第二个边:<br>'; $form .= $this->name.'第三个边:<br>'; $form .= '<br>'; $form .=''; echo $form; } function yan($arr) { $bj = true; if($arr['bian1'] <0) { echo "第一个边不能小于0!<br>"; $bj = false; } if($arr['bian2'] <0) { echo "第二个边不能小于0!<br>"; $bj = false; } if($arr['bian3'] <0) { echo "第三个边不能小于0!<br>"; $bj = false; } if(($arr['bian1']+$arr['bian2'] <$arr['bian3']) || ($arr['bian1'] + $arr['bian3'] <$arr['bian2']) || ($arr['bian2']+$arr['bian3'] <$arr['bian1'])) { echo "两边之和必须大于第三个边"; $bj = false; } return $bj; } }
矩形计算类文件:
class Rect extends Shape { private $width; private $height; function __construct($arr=array()) { if(!empty($arr)) { $this->width = $arr['width']; $this->height = $arr['height']; } $this->name = "矩形"; } function area() { return $this->width * $this->height; } function zhou() { return 2*($this->width + $this->height); } function view() { $form = ''; $form .= $this->name.'的宽:<br>'; $form .= $this->name.'的高:<br>'; $form .= '<br>'; $form .=''; echo $form; } function yan($arr) { $bg = true; if($arr['width'] name."的宽不能小于0!<br>"; $bg = false; } if($arr['height'] name."的高度不能小于0!<br>"; $bg = false; } return $bg; } }
以上就是PHP实现的简单三角形、矩形周长面积计算器分享的详细内容,更多请关注gaodaima搞代码网其它相关文章!