【问题标题】:PHP - Passing functions with arguments as argumentsPHP - 以参数作为参数传递函数
【发布时间】:2018-07-06 12:06:13
【问题描述】:

我有几个具有不同数量参数的可互换函数,例如:

function doSomething1($arg1) {
    …
}

function doSomething2($arg1, $arg2) {
    …
}

我想将一定数量的这些函数连同参数一起传递给另一个处理函数,例如:

function doTwoThings($thing1, $thing2) {
    $thing1();
    $thing2();
}

显然这种语法是不正确的,但我认为它明白了我的意思。处理函数会被这样调用:

doTwoThings(‘doSomething1(‘abc’)’, ‘doSomething2(‘abc’, ‘123’));

所以问题是,这实际上是如何完成的?

根据我的研究,听起来我可以将“doSomething”函数调用“包装”在一个匿名函数中,完成参数并将这些“包装”函数传递给“doTwoThings”函数,因为匿名函数从技术上讲,它们没有参数,它们可以按照上面第二个代码 sn-p 中显示的方式调用。 PHP 文档让我感到困惑,我找到的所有示例都没有将所有内容放在一起。任何帮助将不胜感激!

【问题讨论】:

    标签: php callback arguments anonymous-function


    【解决方案1】:

    您可以使用call_user_func_array(),它接受回调(例如要运行的函数或类方法)并将参数作为数组。

    http://php.net/manual/en/function.call-user-func-array.php

    func_get_args() 表示您可以提供此功能和任意数量的参数。

    http://php.net/manual/en/function.func-get-args.php

    domanythings(
      array( 'thingonename', array('thing','one','arguments') ),
      array( 'thingtwoname', array('thing','two','arguments') )
    );
    
    funciton domanythings()
    {
      $results = array();
      foreach( func_get_args() as $thing )
      {
         // $thing[0] = 'thingonename';
         // $thing[1] = array('thing','one','arguments')
         if( is_array( $thing ) === true and isset( $thing[0] ) and is_callable( $thing[0] ) )
         {
           if( isset( $thing[1] ) and is_array( $thing[1] ) )
           {
             $results[] = call_user_func_array( $thing[0], $thing[1] );
           }
           else
           {
             $results[] = call_user_func( $thing[0] );
           }
         }
         else
         {
           throw new Exception( 'Invalid thing' );
         }
      }
      return $results;
    }
    

    这和做的一样

    thingonename('thing','one','arguments');
    thingtwoname('thing','two','arguments');
    

    【讨论】:

    • 这正是我所需要的,谢谢你把它布置得这么好!
    • 酷,如果你需要调用类方法,你可以使用call_user_func_array(array('className','classMethod'),array('args'))call_user_func_array(array($object,'classMethod'),array('args'))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2013-01-27
    • 2019-11-23
    • 2011-05-11
    • 2014-01-18
    • 1970-01-01
    相关资源
    最近更新 更多