在PHP中,閉包(Closure)是一種可以捕獲其定義時所在作用域中的變量并在稍后執行的匿名函數。以下是創建和使用閉包的示例:
<?php
function outerFunction() {
$message = "Hello, I am outside the closure.";
// 創建一個閉包,捕獲外部作用域中的$message變量
$closure = function () use ($message) {
echo $message;
};
// 調用閉包
$closure(); // 輸出: Hello, I am outside the closure.
}
outerFunction();
?>
在這個例子中,我們首先定義了一個名為outerFunction的函數。在該函數內部,我們聲明了一個名為$message的變量。然后,我們創建了一個閉包,并使用use關鍵字捕獲了外部作用域中的$message變量。最后,我們調用了閉包,它輸出了捕獲到的$message變量的值。