<?php class calculator { protected $x; protected $y; protected $result; function setVar($x, $y) { $this->x = $x; $this->y = $y; } function getSummation() { return $this->x + $this->y; } function getMinus() { return $this->x - $this->y; } function getMultiply() { return $this->x * $this->y; } function getDivide() { ($this->y != 0) ? $this->result = $this->x / $this->y : $this->result = 'cannot calculate'; return $this->result; } function getMod() { ($this->y != 0) ? $this->result = $this->x / $this->y : $this->result = 'cannot calculate'; return $this->result; } function squareRoot() { return sqrt($this->x); } function power() { return pow($this->x, $this->y); } } ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Class calculator</title> <style type="text/css"> body { font-family:Tahoma, Geneva, sans-serif; font-size:12px; } input {font-size:10px; width:80px; } </style> </head> <body> <form action="" method="post"> ตัวตั้ง : <input type="text" name="x" id="x" /><br /><br /> ตัวหาร: <input type="text" name="y" id="y" /><br /><br /> <input type="submit" value="คำนวณ" /><br /><br /> </form> <?php require_once("calculator.class.php"); $endl = "\n"; $cal = new calculator(); (isset($_POST['x'])) ? $x = $_POST['x'] : $x = 0; (isset($_POST['y'])) ? $y = $_POST['y'] : $y = 0; $cal->setVar($x, $y); echo "Summation : $x + $y = ".$cal->getSummation().'<br />'.$endl; echo "Minus : $x - $y = ".$cal->getMinus().'<br />'.$endl; echo "Multiply : $x * $y = ".$cal->getMultiply().'<br />'.$endl; echo "Divide : $x / $y = ".$cal->getDivide().'<br />'.$endl; echo "Mod : $x % $y = ".$cal->getMod().'<br />'.$endl; echo "Square root of $x = ".$cal->squareRoot().'<br />'.$endl; echo "Power : $x power $y = ".$cal->power().'<br />'.$endl; ?> </body> </html>