1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php $n = new Number("123"); echo $n->add(1)->sub(2)->mul(3)->div(4); // 91.5 class Number { private $n; public function numCheck($n) { if (!is_numeric($n)) { throw new Exception("${n}は数値ではありません"); } } public function __construct($n) { $this->numCheck($n); $this->n = floatval($n); } public function __toString() { return '' . $this->n; } public function add($n) { $this->numCheck($n); $this->n += floatval($n); return $this; } public function sub($n) { $this->numCheck($n); $this->n -= floatval($n); return $this; } public function mul($n) { $this->numCheck($n); $this->n *= floatval($n); return $this; } public function div($n) { $this->numCheck($n); if ($n == 0) { // 暗黙の型変換を利用するために等値演算子で比較 throw new Exception('0除算'); } $this->n /= $n; return $this; } } |
1 |
91.5 |