zoukankan      html  css  js  c++  java
  • PHP闭包

    1、理解闭包之前先知道一个PHP的array_walk函数

    <?php
    function myfunction($value,$key)
    {
    echo "The key $key has the value $value<br>";
    }
    $a=array("a"=>"red","b"=>"green","c"=>"blue");
    array_walk($a,"myfunction");
    ?>
    
    结果是:(调用了3次myfunction函数)
    The key a has the value red
    The key b has the value green
    The key c has the value blue
    
    <?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)  
        {  
            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));  
                    //其中constant 返回 上边定义常量的值
                   //跟self::访问一样,self不能再这里使用,所以用上边
                    $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) . "
    ";  
    // The result is 54.29  
    ?>    
    &符号则使用变量的地址(传址)

      

     

  • 相关阅读:
    exciting和excited的具体用法怎么区分
    有理数的简算
    is和do的区别
    五则运算计算规则
    家庭小账本
    等差数列和等比数列(快速求存储年份)
    python argparse命令行参数
    Linux Anaconda安装步骤
    Python用MySQLdb, pymssql 模块通过sshtunnel连接远程数据库
    tornado调用ioloop TracebackFuture实现非堵塞的模块
  • 原文地址:https://www.cnblogs.com/aoxueshou/p/9547330.html
Copyright © 2011-2022 走看看