Search code examples
phpphp4

anonymous functions (lambdas, closures) in PHP 4


Is there a trick in PHP 4 to implement functions which return functions? I expected that the following code would work:

function xxx($a) {
  return function($b) {
    print "a=$a, b=$b \n";
  }
}

$f1 = xxx(1);
$f1(2);

Unfortunately, no luck in PHP 4. Probably it works in PHP 5, but I limited to PHP 4.

I tried to workaround with OO, but again failed (class declarations may not be nested):

class Closure {
  function run($a) {
    print "raise: NotImplementedException, instead: $a\n";
  }
}

class WantCheckNesting extends Closure {
  function run($a, $b) {
    class Nested extends Closure {
      function run($c) {
        print "a=$a, b=$b, c=$c\n";
      }
    }
    $o = new Nested();
    return $o;
  }
}

$d = new WantCheckNesting();
$e = $d->run(2, 3);
$e->run(4);

There is a function "create_function", but it is very limited: the body must be a string.

Any other ideas?


Solution

  • You're probably barking at the wrong tree. PHP is not a functional programming language. Some changes have been made starting with PHP 5.3, but even there you don't have your expected variable scopes that would allow you to do what you have in your examples.

    The only tools you can use in PHP 4 are create_function and some ingenuity to write the function definition as a string.

    <?php
    
    function getMyFunc($a){
      return create_function('$b', 'print "a='.$a.', b=$b";');
    }
    
    $f1 = getMyFunc(1);
    $f1(2);
    
    ?>
    

    ...but even if this is simple for your posted example, it definitely isn't practical for more complex situations.