我怎么能一个PHP函数的参数列表转换为关联数组? [英] How can I convert a PHP function's parameter list to an associative array?

查看:177
本文介绍了我怎么能一个PHP函数的参数列表转换为关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的参数转换为功能于关联数组的钥匙等于参数变量名和值等于参数值。

I want to convert the arguments to a function into an associative array with keys equal to the parameter variable names, and values equal to the parameter values.

PHP:

function my_function($a, $b, $c) {

    // <--- magic goes here to create the $params array

    var_dump($params['a'] === $a); // Should result in bool(true)
    var_dump($params['b'] === $b); // Should result in bool(true)
    var_dump($params['c'] === $c); // Should result in bool(true)
}

我怎样才能做到这一点?

How can I do this?

推荐答案

在你可以做到这一点使用 紧凑

The you can do this using compact:

function myFunc($a, $b, $c) {
    $params = compact('a', 'b', 'c');
    // ...
}

或者, get_defined_vars() 会给你在这范围内,这将工作中定义的所有变量的关联数组,但我认为这也可能包括 $ _ POST $ _ GET ,等...

否则,您可以使用 func_get_args 得到传递给函数的所有参数列表。这是的的关联,虽然,因为它是唯一被传递的数据(也就是,有没有变量名)。这也让你在你的函数的任何数量的参数。

Otherwise, you can use func_get_args to get a list of all the arguments passed to the function. This is not associative though, since it is only data which is passed (that is, there's no variable names). This also lets you have any number of arguments in your function.

或者,只指定一个参数,它是一个数组:

Or, just specify one argument, which is an array:

function myFunc($params) {

}

紧凑型()似乎最接近是你在做什么,虽然之后。

compact() seems to be closest to what you're after though.

这篇关于我怎么能一个PHP函数的参数列表转换为关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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