PHP-以参数作为参数传递函数 [英] PHP - Passing functions with arguments as arguments

查看:158
本文介绍了PHP-以参数作为参数传递函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have several interchangeable functions with different numbers of arguments, for example:

function doSomething1($arg1) {
    …
}

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

我想将一定数量的这些函数(带有参数)传递给另一个处理函数,例如:

I would like to pass a certain number of these functions, complete with arguments, to another handling function, such as:

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

很明显,这种语法是不正确的,但是我认为这很正确.处理函数的名称如下:

Obviously this syntax is not correct but I think it gets my point across. The handling function would be called something like this:

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

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

So the question is, how is this actually done?

从我的研究看来,我也许可以包装"匿名函数中的"doSomething"函数调用,并带有参数,然后将这些包装的"函数传递给"doTwoThings"函数,并且由于该匿名函数从技术上讲,它们没有参数,可以按照上面第二个代码片段中所示的方式来调用它们. PHP文档使我感到困惑,我找不到的所有示例都将所有内容放在一起.任何帮助将不胜感激!

From my research it sounds like I may be able to "wrap" the "doSomething" function calls in an anonymous function, complete with arguments and pass those "wrapped" functions to the "doTwoThings" function, and since the anonymous function doesn't technically have arguments they could be called in the fashion shown above in the second code snippet. The PHP documentation has me confused and none of the examples I'm finding put everything together. Any help would be greatly appreciated!

推荐答案

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

you could make use of call_user_func_array() which takes a callback (eg a function or class method to run) and the arguments as an array.

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

func_get_args()表示您可以输入此函数和任意数量的参数.

The func_get_args() means you can feed this funciton and arbitary number of arguments.

http://php.net/manual/zh/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');

这篇关于PHP-以参数作为参数传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆