1. 程式人生 > >PHP閉包

PHP閉包

函數 fun lse quantity 理解 The public add 其中

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) . "\n";  
// The result is 54.29  
?>    
&符號則使用變量的地址(傳址)

  

 

PHP閉包