首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 閉包函數詳解:匿名函數、use 綁定、類別常數存取與購物車實戰

     編輯:PHP 綜合知識

閉包函數基礎

無名稱函數,指派給變數即可調用:

$cl = function($name) {
    return sprintf('hello %s', $name);
};
echo $cl('fuck'); // 輸出: hello fuck

回調函數應用

echo preg_replace_callback('~-([a-z])~', function($match) {
    return strtoupper($match[1]);
}, 'hello-world'); // 輸出: helloWorld

use 關鍵字:繼承外部變數

$message = 'hello';
$example = function() use ($message) {
    var_dump($message);
};
$example(); // 輸出: hello

$message = 'world';
$example(); // 仍輸出: hello (定義時綁定值)

/* 參考綁定 */
$message = 'hello';
$example = function() use (&$message) {
    var_dump($message);
};
$example(); // hello
$message = 'world';
$example(); // world (參考綁定,隨外部變化)

閉包傳值應用

$message = 'hello';
$example = function($data) use ($message) {
    return "{$data},{$message}";
};
echo $example('world'); // world,hello

購物車完整實戰範例

class Cart {
    // 類別常數定義價格
    const PRICE_BUTTER = 1.00;
    const PRICE_MILK   = 3.00;
    const PRICE_EGGS   = 6.95;

    protected $products = [];

    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.0;
        // 閉包捕獲 $tax (值綁定) 與 $total (參考綁定)
        $callback = function($quantity, $product) use ($tax, &$total) {
            // 存取類別常數:constant(__CLASS__ . "::PRICE_" . strtoupper($product))
            $price = constant(__CLASS__ . "::PRICE_" . strtoupper($product));
            $total += ($price * $quantity) * ($tax + 1.0);
        };
        // array_walk 遍歷陣列,將鍵值作為參數傳給回調
        array_walk($this->products, $callback);
        return round($total, 2);
    }
}

$cart = new Cart();
$cart->add('butter', 1);
$cart->add('milk', 3);
$cart->add('eggs', 6);
echo $cart->getTotal(0.05); // 含 5% 稅

關鍵技術點解析

  1. constant() 動態取得常數值,配合 __CLASS__ 魔術常數
  2. array_walk() 回調函數簽名:function($value, $key),此處對應 ($quantity, $product)
  3. use ($tax, &$total):$tax 為值綁定 (稅率固定),$total 為參考綁定 (累加總額)
  4. 閉包封裝計算邏輯,外部無法直接存取 $total

閉包 vs 類別方法比較

特性閉包類別私有方法
狀態封裝透過 use 參考綁定透過 $this-> 屬性
可攜性可作為參數傳遞、回傳綁定於類別實例
語法簡潔度內聯定義較簡潔需額外定義方法
效能略低 (閉包物件開銷)略高

適用場景建議

  • 一次性回調:array_map/walk/filter, preg_replace_callback, usort
  • 事件監聽/中介軟體:閉包鏈、管道模式
  • 延遲執行/策略模式:將算法封裝為閉包注入
  • 複雜業務邏輯:優先使用類別方法,可測試性更好
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved