了解 PHP 中的高阶函数

Understanding higher order functions in PHP

我觉得这段代码很难理解。如果我能通过插图和细节理解这一点,我将不胜感激。

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

function get_algorithm($rand_seed_fnc) {
    return (odd_even($rand_seed_fnc())) ?
        function($value) {
           return $value * $value;
        } :
        function($value) use ($rand_seed_fnc) {
            return ($value * $value / $rand_seed_fnc()) + 10;
        };
}

function odd_even($value) {
    return ($value % 2 === 0);
}

$rand_seed_fnc = function() { return rand(); };
$results = array_map(get_algorithm($rand_seed_fnc), $data);

var_dump($results);

多个 return 的使用、闭包、混淆、格式错误、嵌套函数、未使用的变量都出现在您的示例中。 根据我的测试,它也不总是 return 返回相同的值( floats )。

我重写了它以展示逻辑背后的意图,并且花了一些时间来解开 get_algorithm 调用中未使用的 $rand_seed_fnc 和变量赋值的可怕函数。

<?php
    // Data to run functions on.
    $data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    function get_algorithm( $iValue ) 
    {
        // Check if value is odd or even and return a different value.
        // Replaces odd_even function.
        // Uses modulus %
        // $value = 1, returns FALSE;
        // $value = 2, returns TRUE;
        // $value = 3, returns FALSE;
        // $value = 4, returns TRUE;
        if( $iValue % 2 === 0 )
        {
            // Square the value if it's even.
            $iReturn = $iValue * $iValue;
        }
        else
        {
            // Square the value and divide by a random number then add 10.
            $iReturn = ( $iValue * $iValue / rand() ) + 10;
        }
        return $iReturn;
    }
    $results = array_map( 'get_algorithm', $data );
    var_dump($results);
?>