ITPub博客

首页 > IT职业 > IT生活 > PHP匿名函数

PHP匿名函数

IT生活 作者:yifanwu 时间:2021-09-09 09:19:40 0 删除 编辑

// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。

// 其中有一个方法用来计算购物车中所有商品的总价格,该方法使

// 用了一个 closure 作为回调函数。

class Cart

{

    const PRICE_BUTTER  = 1.00;

    const PRICE_MILK    = 2.00;

    const PRICE_EGGS    = 3.00;

 

    protected   $products = array();

     

    public function add($product, $quantity)

    {

        $this->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;

 

// 往购物车里添加条目

$my_cart->add('butter', 1);

$my_cart->add('milk', 2);

$my_cart->add('eggs', 3);

 

// 打出出总价格,其中有 5% 的销售税.

print $my_cart->getTotal(0.05) . "n";

// 最后结果是 14.7 

?>

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2157/viewspace-2802240/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-24

  • 博文量
    84
  • 访问量
    12526