【问题标题】:Array of variables to function parameter [duplicate]函数参数的变量数组[重复]
【发布时间】:2016-05-20 14:37:10
【问题描述】:

我有一个这样的数组:

$params = ["Hello" => "Hello World", "Text" => "This is a text"];

我想调用函数:

myFunction("Hello World", "This is a text");

我该怎么做?

【问题讨论】:

标签: php arrays function parameters


【解决方案1】:

您正在寻找call_user_func_array():

call_user_func_array('myFunction', $params);

或者如果你有 PHP 5.6+,你可以使用... 操作符:

myFunction(...$params);

注意:这只适用于 numeric 数组,不适用于 associative 数组

【讨论】:

    【解决方案2】:
    $params = ["Hello" => "Hello World", "Text" => "This is a text"];
    

    使用call_user_func_array

    call_user_func_array('myFunction', array_values($params));
    

    你也可以这样做:

    myFunction($params['Hello'], $params['Text']);
    
    function myFunction($h, $t){
        echo $h." - ".$t;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多