如何将 PHP 函数的参数列表转换为关联数组? [英] How can I convert a PHP function's parameter list to an associative array?

查看:27
本文介绍了如何将 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)
}

我该怎么做?

推荐答案

你可以使用 compact:

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() 似乎最接近你所追求的.

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

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

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