为什么应该更喜欢 call_user_func_array 而不是常规调用函数?

2022-01-03 00:00:00 function callback php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2
";
}
foobar('one','two'); // OUTPUTS : foobar got one and two 

call_user_func_array("foobar", array("one", "two")); // // OUTPUTS : foobar got one and two 

正如我看到的常规方法和 call_user_func_array 方法都输出相同,那为什么要更喜欢它?

As I can see both regular one and call_user_func_array method both outputs same, then why should one prefer it?

在哪种情况下,常规调用方法会失败而call_user_func_array 不会?

In which scenario regular calling method will fail but call_user_func_array will not?

我能举出这样的例子吗?

Can I get any such example?

谢谢

推荐答案

  1. 您有一个包含不确定长度的函数参数的数组.

  1. You have an array with the arguments for your function which is of indeterminate length.

$args = someFuncWhichReturnsTheArgs();

foobar( /* put these $args here, you do not know how many there are */ );

替代方案是:

switch (count($args)) {
    case 1:
        foobar($args[0]);
        break;
    case 2:
        foobar($args[0], $args[1]);
        break;
    ...
}

这不是解决方案.

这种用例可能很少见,但是当您遇到它时,您需要它.

The use case for this may be rare, but when you come across it you need it.

相关文章