PHP 手冊中的匿名函式關聯用法分析

Latent發表於2019-09-11

1.匿名函式

匿名函式 也叫 閉包函式(closures),可以建立一個沒有指定名稱的函式,一般作用於回撥函式(callback)引數的值。匿名函式目前是透過 Closure 類來實現的。

1.我們平時可能用到的相關函式舉例


<?php
//array_reduce 將回撥函式 callback 迭代地作用到 array 陣列中的每一個單元中,從而將陣列簡化為單一的值。
$array = [1, 2, 3, 4];
$str = array_reduce($array, function ($return_str, $value) {
    $return_str = $return_str . $value;  //層層迭代
    return $return_str;
});
//1.第一次迭代  $return_str = '',value = '1' 返回 '1'
//2.第二次迭代  $return_str = '1',value = '2'  返回 '12'
//3.第三次迭代  $return_str = '12',value = '3'  返回 '123'
//4.第四次迭代  $return_str = '123',value = '4'  返回 '1243'
var_dump($str);
// string('12345')
// array_walk — 使用使用者自定義函式對陣列中的每個元素做回撥處理 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br/>\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');

?>

2.實際業務用法

<?php
// 一個基本的購物車,包括一些已經新增的商品和每種商品的數量。
// 其中有一個方法用來計算購物車中所有商品的總價格,該方法使
// 用了一個 closure 作為回撥函式。
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));
                $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";
// 最後結果是 54.29
?> 

---- 以上內容來自官方手冊,可供參考

本作品採用《CC 協議》,轉載必須註明作者和本文連結
不成大牛,不改個簽

相關文章