简体   繁体   中英

Using lambda and closure together in PHP

I am trying to understand the use of these two lambda and closure function. But can't understand it properly. It would be great if i could understand it with illustration and details.

 $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)

Readable translated version hope it helps in understanding lambdas ( php anonymous function ) and closures ( anonymous function with access to variables ) better.

Reference: 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)
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM