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 getTotal($tax)
    {
        $total = 0.00;
        $callback = function ($quantity, $product) use ($tax, &$total)
        {
            $priceItem = constant(__CLASS__."::PRICE_".strtoupper($product));
            $total += ($priceItem*$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);
print_r($my_cart->getTotal(0.05));

又一次长知识了,666!