2008-12-07 ================================================================================ ■例題 レストランの支払い レストランで3人が食事をしました。 ひとりはラーメン(500円)、2人はカレー(600円)です。 支払額の合計はいくらになるかを算出するアプリケーションをつくります。 ■カプセル化未対応 □amount.php --- price = 500; $r_detail = new Detail(); $r_detail->product = $ramen; $r_detail->quantity = 1; // カレーオブジェクトとカレー明細オブジェクトを設定する $currey = new Product(); $currey->price = 600; $c_detail = new Detail(); $c_detail->product = $currey; $c_detail->quantity = 2; // ラーメン明細オブジェクト、カレー明細オブジェクトを伝票に設定する $order = new Order(); $order->details[] = $r_detail; $order->details[] = $c_detail; // 支払額を算出し、表示する print "支払額: {$order->getAmount()}"; print "

1.0 カプセル化未対応

"; ?> --- □Order.class.php --- details as $detail) { $totalAmount += $detail->getAmount(); } return $totalAmount; } } ?> --- □Detail.class.php --- quantity * $this->product->getPrice(); } } ?> --- □Product.class.php --- price; } } ?> --- ■カプセル化対応 カプセル化します。 ついでに、PHPドキュメント用にコメントも記します。 □amount.php --- add($r_detail); $order->add($c_detail); // 支払額を算出し、表示する print "支払額: {$order->getAmount()}"; print "

1.1 カプセル化対応

"; ?> --- □Order.class.php --- details as $detail) { $totalAmount += $detail->getAmount(); } return $totalAmount; } /** * 指定された明細をこの伝票に追加します。 * @param $detail 追加する明細 */ public function add($detail) { $this->details[] = $detail; } } ?> --- □Detail.class.php --- setProduct($product); $this->setQuantity($quantity); } /** * 商品の定価に個数を乗じた金額を取得します。 * @return 金額 */ public function getAmount() { return $this->quantity * $this->product->getPrice(); } /** * 商品を設定します。 * @param $product 商品 */ public function setProduct($product) { $this->product = $product; } /** * 個数を取得します。 * @param $quantity 個数 */ public function setQuantity($quantity) { $this->quantity = $quantity; } } ?> --- □Product.class.php --- setPrice($price); } /** * 定価を取得します。 * @return 定価 */ public function getPrice() { return $this->price; } /** * この商品の定価を設定します。 * @param $price 定価 */ public function setPrice($price) { $this->price = $price; } } ?> ---