dqmdlo9674 2010-11-11 14:15 采纳率: 100%
浏览 50
已采纳

PHP 4中的匿名函数(lambdas,closures)

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 
";
  }
}

$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
";
  }
}

class WantCheckNesting extends Closure {
  function run($a, $b) {
    class Nested extends Closure {
      function run($c) {
        print "a=$a, b=$b, c=$c
";
      }
    }
    $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?

  • 写回答

2条回答 默认 最新

  • dongxun6690 2010-11-11 14:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号