why should one prefer call_user_func_array over regular calling of function?

前端 未结 6 2047
轮回少年
轮回少年 2020-12-12 20:41
function foobar($arg, $arg2) {
    echo __FUNCTION__, \" got $arg and $arg2\\n\";
}
foobar(\'one\',\'two\'); // OUTPUTS : foobar got one and two 

call_user_func_arr         


        
6条回答
  •  遥遥无期
    2020-12-12 20:59

    As of php 5.6, to pass an array instead of an argument list to a function simply precede the array with an ellipsis (this is called "argument unpacking").

    function foo($var1, $var2, $var3) {
       echo $var1 + $var2 + var3;
    }
    
    $array = [1,2,3];
    
    foo(...$array);  // 6
    // same as call_user_func_array('foo',$array);
    

    The difference between call_user_func_array() and variable functions as of php 5.6 is that variable functions do not allow you to call a static method:

    $params = [1,2,3,4,5];
    
    function test_function() {
      echo implode('+',func_get_args()) .'='. array_sum(func_get_args())."\r\n";
    }    
    
    // Normal function as callback
    $callback_function = 'test_function';
    call_user_func_array($callback_function,$params); // 1+2+3+4+5=15
    $callback_function(...$params); // 1+2+3+4+5=15
    
    class TestClass
    {
      static function testStaticMethod() {
        echo implode('+',func_get_args()) .'='. array_sum(func_get_args())."\r\n";
      }
    
      public function testMethod() {
        echo implode('+',func_get_args()) .'='. array_sum(func_get_args())."\r\n";
      }
    }
    
    // Class method as callback
    $obj = new TestClass;
    $callback_function = [$obj,'testMethod'];
    call_user_func_array($callback_function,$params); // 1+2+3+4+5=15
    $callback_function(...$params); // 1+2+3+4+5=15
    
    // Static method callback
    $callback_function = 'TestClass::testStaticMethod';
    call_user_func_array($callback_function,$params); // 1+2+3+4+5=15
    $callback_function(...$params); // Fatal error: undefined function
    

    Php 7 adds the ability to call static methods via a variable function, so as of php 7 this difference no longer exists. In conclusion, call_user_func_array() gives your code greater compatibility.

提交回复
热议问题