了解 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);

示例中存在多个返回、闭包、混淆、格式错误、嵌套函数、未使用的变量的使用。根据我的测试,它也没有始终如一地返回相同的值(浮点数)。

我重写了它以演示逻辑背后的意图,并且花了一点时间才解开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);
?>