新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
聊聊php閉包官方寫法有什么好處
php閉包官方寫法有什么好處 ?

具體問題描述:
products[$product] = $quantity;
}
public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$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;
// 往購物車?yán)锾砑訔l目
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// 打出出總價格,其中有 5% 的銷售稅.
print $my_cart->getTotal(0.05) . "\n";
// 最后結(jié)果是 54.29
?>
Copy
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
這段代碼和 foreach 來做有什么區(qū)別那?循環(huán)次數(shù)和規(guī)模應(yīng)該是一樣的?
回答:
可以讓代碼能更多的被復(fù)用,讓提供的功能具有更多可能性。
比如排序,無非就是比較大小,然后交換位置,交換位置的邏輯是統(tǒng)一的,但是比大小就存在很多情況,所以就會提供閉包回調(diào),讓使用它的地方可以自己決定誰大誰小。
另一個就是通過一些基本方法,讓代碼更具可讀性。
比如你的列子里改成 array_reduce 應(yīng)該更貼切點,這樣別人一看,大概就能意識到,你這段是要計算什么值到單一變量。不過最好就直接把閉包函數(shù)寫在參數(shù)里。
對于數(shù)組的遍歷,在早期的時候,foreach 會有很多問題,不當(dāng)?shù)氖褂?,會制造不必要?bug。
比如
// 這樣用,可能會在后續(xù)的邏輯中出現(xiàn)bug
foreach ($arr as &$item) {
$item['ddd'] = 'ddd';
}
// 這樣用,就可以避免
array_walk($arr, function (&$item) {
$item['ddd'] = 'ddd';
});
反正就是有利有弊,速度當(dāng)然會有影響。
當(dāng)前名稱:聊聊php閉包官方寫法有什么好處
文章分享:http://fisionsoft.com.cn/article/djgoohd.html


咨詢
建站咨詢
