HOWTO · PHP
PHP 中的 Lambda 函式
本教程演示如何在 PHP 中使用 lambda 或匿名函式。
本頁內容
PHP 中的 Lambda 函式是匿名函式,可以儲存在變數中或作為引數傳遞給其他函式。
closure 是一種 lambda 函式,應該知道它的周圍環境,但不是每個 lambda 都是 closure。
Lambda 需要一個臨時函式,該函式將被使用一次。
在 PHP 中演示如何將 Lambda 函式作為引數傳遞
<?php
$demo_array=array(4,3,1,2,8,9,3,10,5,13);
//usort is a built-in PHP function to sort an array with a given condition.
usort($demo_array, function ($a, $b) {
return ($a<$b)?-1:1;
});
// We passed an anonymous function that sorts the array in ascending order; this function is the lambda function.
foreach($demo_array as $val){
echo $val;
echo "<br>";
}
?>
usort() 是一個內建的 PHP 函式,它接受一個陣列和一個函式作為引數;該函式應包含你要對陣列進行排序的條件。
上面的程式碼嘗試在給定的 lambda 函式的幫助下按升序對陣列進行排序。
輸出:
1
2
3
3
4
5
8
9
10
13
在 PHP 中演示如何的變數中儲存 Lambda 函式
PHP 中 lambda 函式的其他功能可以儲存在變數中。
<?php
$divide = function ($a, $b) {
return $a / $b;
};
echo $divide(10, 2);
echo "<br>";
echo $divide(15, 2);
echo "<br>";
echo $divide(10, 3);
echo "<br>";
?>
上面的程式碼建立了一個 lambda 函式,可以將兩個數字相除並將它們儲存為變數。現在它可以在附近的任何地方用作變數。
輸出:
5
7.5
3.3333333333333
PHP 中 Lambda 和 Closure 函式之間的區別
每個 closure 函式都是 lambda 函式,但不是每個 lambda 都是 closure 函式。closure 函式需要了解其周圍環境。
<?php
$range = range(10, 20);
//Print the squared number from 10-20 range - an example of lambda.
echo "The output for lambda function: <br>";
print_r(array_map(function($number){
return $number**2;
}, $range));
echo "<br><br>";
$power = 2;
//Print a warning.
print_r(array_map(function($number){
return $number**$power;
}, $range));
echo "<br><br>";
//Print the squared number from 10-20 range - an example of closure.
echo "The output for closure function: <br>";
print_r(array_map(function($number) use($power) {
return $number**$power;
}, $range));
?>
第二個例子是我們試圖通過一個變數對數字進行平方,但它不能;這就是 closure 函式的作用。
我們使用 use 關鍵字將變數傳遞給函式。現在,這個 lambda 函式是一個 closure 函式。
輸出:
The output for lambda function:
Array ( [0] => 100 [1] => 121 [2] => 144 [3] => 169 [4] => 196 [5] => 225 [6] => 256 [7] => 289 [8] => 324 [9] => 361 [10] => 400 )
Notice: Undefined variable: power in C:\Apache24\htdocs\test.php on line 15
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1 [10] => 1 )
The output for closure function:
Array ( [0] => 100 [1] => 121 [2] => 144 [3] => 169 [4] => 196 [5] => 225 [6] => 256 [7] => 289 [8] => 324 [9] => 361 [10] => 400 )
middle 函式無法對數字進行平方,因為它無法識別外部變數。我們使用 use 關鍵字傳遞變數,然後 lambda 變成 closure 函式。