rakibtg rakibtg - 4 months ago 27
PHP Question

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
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));


It will print this:

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
)

Answer

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, ...]);

A shortcut for this is:

bulkParam(compact('d1', 'd2'));

Then use an array:

function bulkParam(array $params) {
    foreach ($params as $key => $value) ...
}

As Mark mentions in the comments, sometimes you don't even have variables in the first place:

bulkParam('foo');
bulkParam(foo(bar(baz())));

Now what?

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.

Comments