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

查看:37
本文介绍了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/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');

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

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