【问题标题】:how to pass params to a function that gets returned? [closed]如何将参数传递给返回的函数? [关闭]
【发布时间】:2013-09-19 21:15:32
【问题描述】:
function callme() {
    //stuff
    return function($type = '%') use (&$data) {
        //stuff goes here
        return $data;
    };
}

如何传递参数以覆盖$type

我只需要一些例子。

【问题讨论】:

  • 您的意思是将参数传递给callme
  • 不,到返回函数...替换%字符串
  • 是的,但是用什么替换'%'?有你传递给callme 的东西吗?还有别的吗?

标签: php function lambda functional-programming return


【解决方案1】:

首先你调用callme() 来获取函数。然后你调用函数并传递一个参数:

$fn = callme();
$fn("whatever you want to pass");

【讨论】:

  • 这很容易...谢谢:)
【解决方案2】:

当我读到这个问题时,我明白了,因为您想传递返回函数中的默认值。我想:

function callme($default_type = '%') {
    //stuff
    return function($type = $default_type) use (&$data) {
        print "$type\n";
        //stuff goes here
        return $data;
    };
}

但这是一个语法错误。那么最好的方法就是这样做:

function callme($default_type = '%') {
    //stuff
    return function($type = null) use (&$data, $default_type) {
        if( $type === null )
                $type = $default_type;

        print "$type\n";
        //stuff goes here
        return $data;
    };
}

$fn = callme("maybe");
$fn();                   // prints "maybe"
$fn("Carly Rae Jepsen"); // prints "Carly Rae Jepsen"

【讨论】:

    【解决方案3】:
    call_user_func(callme(), 'type argument here');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2020-05-15
      • 2015-07-22
      相关资源
      最近更新 更多