Search code examples
phpfunctionanonymous

How to bind make Currying with PHP? (like Function.prototype.bind do in javascript)?


i want https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Currying in PHP:

$x = function ($a, $b) {
  echo $a . ' ' . $b;
};

for ($i= 0;$i< 10;$i++) {
  $y = bind($x, $i)// how?
  $y($i);
}

Solution

  • Actual currying is maybe a bit of a stretch for PHP (;-)), nonetheless you can do stuff like this with Closures in PHP 5.3+:

    function populatedList() {
        $args = func_get_args();
        return function () use ($args) {
            $localArgs = func_get_args();
            return array_merge($args, $localArgs);
        };
    }
    
    $sevenList = populatedList(7, 14, 21);
    
    var_dump($sevenList('foo', 'bar', 'baz'));
    
    // Array
    // (
    //    [0] => 7
    //    [1] => 14
    //    [2] => 21
    //    [3] => foo
    //    [4] => bar
    //    [5] => baz
    // )