在func_get_args()中具有变量名 [英] Having the variable names in func_get_args()
问题描述
由于此函数可以接受未知数量的参数:
As this function can take unknown numbers of parameters:
function BulkParam(){
return func_get_args();
}
A print_r
将仅打印值,但是我如何检索变量名以及数组键?例如:
A print_r
will print only the values, but how i can retrieve the variable names as well as the array key? For example:
$d1 = "test data";
$d2 = "test data";
$d3 = "test data";
print_r(BulkParam($d1, $d2, $d3));
它将打印以下内容:
Array
(
[0] => test data
[1] => test data
[2] => test data
)
但是我想将变量名作为所有数组的索引名或键名.然后该数组将如下所示:
But i want to have the variables name as the index name or key name of all arrays. Then the array would look like this:
Array
(
[d1] => test data
[d2] => test data
[d3] => test data
)
推荐答案
您不能.变量名称不会传递到函数中.变量是特定算法局部的占位符,它们不是 data ,并且它们在另一个范围内没有意义,也不会被传递.如果需要键值对,则传递一个显式命名的关联数组:
You can not. Variable names are not passed into functions. Variables are placeholders local to a specific algorithm, they are not data and they do not make sense in another scope and are not passed around. Pass an explicitly named associative array if you need key-value pairs:
bulkParam(['d1' => $d1, 'd2' => $d2, ...]);
快捷方式的原因是:
bulkParam(compact('d1', 'd2'));
然后使用数组:
function bulkParam(array $params) {
foreach ($params as $key => $value) ...
}
正如Mark在评论中提到的那样,有时您甚至根本没有变量:
As Mark mentions in the comments, sometimes you don't even have variables in the first place:
bulkParam('foo');
bulkParam(foo(bar(baz())));
现在呢?
或者最终,您将需要重构代码并更改变量名:
Or eventually you'll want to refactor your code and change variable names:
// old
$d1 = 'd1';
bulkParam($d1);
// new
$userName = 'd1';
bulkParam($userName);
您的应用程序行为不应仅因为重命名变量而改变.
Your application behaviour should not change just because you rename a variable.
这篇关于在func_get_args()中具有变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!