zoukankan      html  css  js  c++  java
  • 关于匿名函数的使用,购物车中计算销售税的应用

    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!

  • 相关阅读:
    P2610 [ZJOI2012]旅游
    P2323 [HNOI2006]公路修建问题
    P3629 [APIO2010]巡逻
    ARC059F
    AGC004D Teleporter
    p3203 弹飞绵羊
    bzoj5450 轰炸
    bzoj4313 三维积木
    cf123E Maze
    bzoj4423 [AMPPZ2013]Bytehattan
  • 原文地址:https://www.cnblogs.com/sien6/p/7103725.html
Copyright © 2011-2022 走看看