Get an associative parameter array for a function defined without predefined function parameters

Viewed 23

Is it possible to get an associative parameter array for a function defined without predefined function parameters.

Lets assume the following function:

function foo()
{
   print_r(func_get_args());
}

Example:

$a = "bar";
$b = "baz";

foo($a, $b);

Results in:

Array
(
    [0] => "bar"
    [1] => "baz"
)

The desired outcome would be:

Array
(
    [a] => "bar"
    [b] => "baz"
)

Tried so far:

PHP's ReflectionFunction will only return foo's predefined parameters, not its dynamically defined parameters.

1 Answers

I think it's possible by passing an associative array as a parameter:

<?php
function foo(array $args = array()) {
    print_r($args);
}

foo(
    array(
    'a' => 'bar',
    'b' => 'baz'
    )
);

Results:

Array
(
    [a] => bar
    [b] => baz
)

And with defined parameters, you can try get_defined_vars(). "Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list."

<?php
function foo($a, $b)
{
   print_r(get_defined_vars());
}
$a = "bar";
$b = "baz";

foo($a, $b);

Results: Array

(
    [a] => bar
    [b] => baz
)
Related