<?php
$closure = function ($param) use ($externalVar) {
// 函數體
};
// 箭頭函數 (PHP 7.4+)
$fn = fn($x) => $x * 2;
use 關鍵字將外部變數「捕獲」進閉包作用域。
<?php
$msg = 'Hello';
$byVal = function() use ($msg) { echo $msg; }; // 捕獲當前值 'Hello'
$byRef = function() use (&$msg) { echo $msg; }; // 捕獲變數參考
$msg = 'World';
$byVal(); // Hello
$byRef(); // World
<?php
class Cart {
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
protected $products = [];
public function add($product, $qty) { $this->products[$product] = $qty; }
public function getTotal($tax) {
$total = 0.0;
$callback = function($qty, $product) use ($tax, &$total) {
$price = constant('self::PRICE_' . strtoupper($product));
$total += ($price * $qty) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
}
<?php
function html($tag, $id='', $class='') {
$attrs = '';
if ($id) $attrs .= " id=\"$id\"";
if ($class) $attrs .= " class=\"$class\"";
$open = "<$tag$attrs>";
$close = "</$tag>";
return function($inner='') use ($open, $close) {
return "$open$inner$close";
};
}
$div = html('div', 'main', 'container');
echo $div('Content'); // <div id="main" class="container">Content</div>
<?php
$fib = function($n) use (&$fib) {
if ($n <= 1) return 1;
return $fib($n-1) + $fib($n-2);
};
echo $fib(10); // 89
// 關鍵:use (&$fib) 參考捕獲,否則 $fib 尚未定義時無法在閉包內呼叫自身
<?php
$result = 0;
$lazy = function() use (&$result) { return $result; };
$eager = function() use ($result) { return $result; };
$result = 42;
echo $lazy(); // 42 (參考)
echo $eager(); // 0 (值捕獲時刻為 0)
Closure::bindTo($newThis, $newScope):複製閉包並綁定新 $this 與作用域。Closure::call($thisArg, ...$args):臨時綁定 $this 執行 (PHP 7+)。Closure::fromCallable():從可呼叫物建立閉包。__invoke()。