在 PHP 中一起使用 lambda 和闭包
Using lambda and closure together in PHP
我正在尝试了解这两个 lambda 和闭包函数的用法。但是不能正确理解。如果我能通过插图和细节来理解它,那就太好了。
$array = array(12345, 'abcde');
$lambda = function($value) { return md5($value); };
$closure = function($value) use ($lambda) {
return 'MD5 Hash: ' . $lambda($value);//what is $lambda($value) here?
};
$result = array_map($closure, $array);
var_dump($result);
//array (size=2)
//0 => string 'MD5 Hash: 827ccb0eea8a706c4c34a16891f84e7b' (length=42)
//1 => string 'MD5 Hash: ab56b4d92b40713acc5af89985d4b786' (length=42)
可读的翻译版本希望它有助于更好地理解 lambdas(php 匿名函数)和闭包(可以访问变量的匿名函数)。
参考:http://php.net/manual/en/class.closure.php
<?php
$array = array(12345, 'abcde');
// Returns a value's md5.
function getNonLambdaMd5( $value )
{
return md5($value);
}
// Pre-pends 'MD5 Hash: ' text to md5 values.
function getNonClosureWrapperText( $value )
{
return 'MD5 Hash: ' . getNonLambdaMd5( $value );
}
// Array_Map replacer to loop through all values within the array.
$iCountValues = count( $array );
for( $i = 0; $i < $iCountValues; ++$i )
{
// Add each to the result.
$result[] = getNonClosureWrapperText( $array[ $i ] );
}
var_dump($result);
//array (size=2)
//0 => string 'MD5 Hash: 827ccb0eea8a706c4c34a16891f84e7b' (length=42)
//1 => string 'MD5 Hash: ab56b4d92b40713acc5af89985d4b786' (length=42)
?>
我正在尝试了解这两个 lambda 和闭包函数的用法。但是不能正确理解。如果我能通过插图和细节来理解它,那就太好了。
$array = array(12345, 'abcde');
$lambda = function($value) { return md5($value); };
$closure = function($value) use ($lambda) {
return 'MD5 Hash: ' . $lambda($value);//what is $lambda($value) here?
};
$result = array_map($closure, $array);
var_dump($result);
//array (size=2)
//0 => string 'MD5 Hash: 827ccb0eea8a706c4c34a16891f84e7b' (length=42)
//1 => string 'MD5 Hash: ab56b4d92b40713acc5af89985d4b786' (length=42)
可读的翻译版本希望它有助于更好地理解 lambdas(php 匿名函数)和闭包(可以访问变量的匿名函数)。
参考:http://php.net/manual/en/class.closure.php
<?php
$array = array(12345, 'abcde');
// Returns a value's md5.
function getNonLambdaMd5( $value )
{
return md5($value);
}
// Pre-pends 'MD5 Hash: ' text to md5 values.
function getNonClosureWrapperText( $value )
{
return 'MD5 Hash: ' . getNonLambdaMd5( $value );
}
// Array_Map replacer to loop through all values within the array.
$iCountValues = count( $array );
for( $i = 0; $i < $iCountValues; ++$i )
{
// Add each to the result.
$result[] = getNonClosureWrapperText( $array[ $i ] );
}
var_dump($result);
//array (size=2)
//0 => string 'MD5 Hash: 827ccb0eea8a706c4c34a16891f84e7b' (length=42)
//1 => string 'MD5 Hash: ab56b4d92b40713acc5af89985d4b786' (length=42)
?>