Categories
PHP

PHP currying – delayed argument binding

To access a local variable within a callback, use currying (delayed argument binding). For example

function curry($func, $arity) {
    return create_function('', "
        $args = func_get_args();
        if(count($args) >= $arity)
            return call_user_func_array('$func', $args);
        $args = var_export($args, 1);
        return create_function('','
            $a = func_get_args();
            $z = ' . $args . ';
            $a = array_merge($z,$a);
            return call_user_func_array('$func', $a);
        ');
    ");
}

function sum($a, $b) {
    return $a + $b;
}

$sum = curry('sum', 2);
$plus5 = $sum(5);
echo $plus5(10); // 15

$map = curry('array_map', 2);
$toupper = $map('strtoupper');
$ary = array('haskell', 'curry',);
print_r($toupper($ary)); // HASKELL CURRY

via http://www.sitepoint.com/forums/showthread.php?336758-example-of-a-callback-in-PHP

Or perfect for preg_replace_callback:

function curry($func, $arity) {
    return create_function('', "
        $args = func_get_args();
        if(count($args) >= $arity)
            return call_user_func_array('$func', $args);
        $args = var_export($args, 1);
        return create_function('','
            $a = func_get_args();
            $z = ' . $args . ';
            $a = array_merge($z,$a);
            return call_user_func_array('$func', $a);
        ');
    ");
}

function on_match($transformation, $matches)
{
    return $transformation[strtolower($matches[1])];
}

$transform = array('a' => 'Well,', 'd'=>'whatever', 'b'=>' ');

$callback = curry(on_match, 2);
echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');

echo "n";

via http://www.php.net/manual/en/function.preg-replace-callback.php#88013