在 func_get_args() 中有变量名 [英] Having the variable names in func_get_args()

查看:22
本文介绍了在 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
)

推荐答案

你不能.变量名不会传递给函数.变量是特定算法的本地占位符,它们不是数据,它们在另一个范围内没有意义,也不会被传递.如果需要键值对,请传递显式命名的关联数组:

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屋!

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