array_walkの使い方
クロージャ
↓
use の使い方
↓
callback
と行き着いた で、サンプルに記載のあるarray_walkに出会う
しらなかったらforeachで回して。って実装をするような部分。
array_walk( array , callable ) でarrayの内容を引数にしたcallback関数を実装する事が出来る
callable には arrayの value / key を第1,第2引数として渡す事ができる (key / value の順ではない)
php.netのsampleが秀逸 で、こういう実装をしたいな。と惚れて読んだ。
次回、こういう処理があったらクロージャを使って実装しようと思う
PHP: 無名関数 - Manual
<?php // 基本的なショッピングカートで、追加した商品の一覧や各商品の // 数量を表示します。カート内の商品の合計金額を計算するメソッド // では、クロージャをコールバックとして使用します。 class Cart { const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $products = array(); public function add($product, $quantity) { $this->products[$product] = $quantity; } public function getQuantity($product) { echo "test"; return isset($this->products[$product]) ? $this->products[$product] : FALSE; } public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { echo $quantity; echo $product; $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); } } $my_cart = new Cart; // カートに商品を追加します $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // 合計に消費税 5% を付加した金額を表示します print $my_cart->getTotal(0.05) . "\n"; // 結果は 54.29 です ?>