dton37910 2013-10-11 10:38
浏览 30
已采纳

php中的函数式编程

So I've been writing this class in php (first timer) that has a function that returns a function based on a parameter and it looks something like this:

$f=function($a){
    return function($b){
        return $a.$b;
    };
};

echo $f('a')('b');

but I can't figure out why it doesn't do what I want. Does anyone know the best way to do this?

Basically I need to write a function that takes a string ($type) and writes a function that takes some other strings and turns them into a html input like so:

public static function InputFormat($t){
    return function ($f, $p, $e){
        return 
            "<div class='inputformat' id='".$f."'>".
                "<ul>".
                    "<li id='namefield'>".$f."</li>".
                    "<li id='input'><input name='".$f."' type='".$t."' value='".$p."'></li>".
                    "<li id='error'>".$e."</li>".
                "<ul>".
            "</div>";
    };
}
  • 写回答

1条回答 默认 最新

  • drh37116 2013-10-11 10:57
    关注

    First, your function does not look good.

    You function should look so:

    $f = function($a){
       return function ($a) use ($b) {
                return $a.$b;
             };
    };
    

    Second: you can't call your function like $f('a')('b');. You call your function this way:

    $f2 = $f('a');
    echo $f2('b');
    

    This is how closure work in php!

    I hope this will help you. Ask me if you have questions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装