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.

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

报告相同问题?