在PHP中一起使用lambda和closure

时间:2015-03-08 15:17:31

标签: php lambda closures

我试图了解这两个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)

1 个答案:

答案 0 :(得分:0)

可读翻译版本希望它有助于理解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)
?>