Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force results of func_get_args() to be an associative array instead of 0-index

Tags:

php

arguments

Was wondering if it's possible to make a call like func_get_args() (reference) but instead of resulting in a 0-index array, result in an associative array, using the variable names as the keys?

For example:

function foo($arg1, $arg2)
{
    var_dump(func_get_args());
}

foo('bar1', 'bar2');

// Output
array(2) {
  [0]=>
  string(4) "bar1"
  [1]=>
  string(4) "bar2"
}

// Preferred
array(2) {
  [arg1]=>
  string(4) "bar1"
  [arg2]=>
  string(4) "bar2"
}

The reason I ask, is I need to validate that these args, passed as an array, to a RPC function, are actually populated. And it seems to be it's better to be specific about the contents rather than hoping they were passed in correct order:

// Now
if (array_key_exists(0, $args)) {

// Preferred
if (array_key_exists('arg1', $args)) {

It would be easy for me to create an assoc array from the args passed in to the original function before passing off to RPC, but was just wondering if there were an already compiled function to do it for me.

Thanks.

-- Edit --

Sorry, I forgot to mention that the code I am touching already exists, which means I cannot change the function signature.

like image 371
Mike Purcell Avatar asked Feb 08 '12 18:02

Mike Purcell


2 Answers

You can make use of get_defined_varsDocs at the very beginning of your function so that it contains only the passed (and defined) arguments:

function foo($arg1, $arg2)
{
    var_dump(get_defined_vars());
}

foo('bar1', 'bar2');

Output (Demo):

array(2) {
  ["arg1"]=>
  string(4) "bar1"
  ["arg2"]=>
  string(4) "bar2"
}

If you're making use of static or global variables inside the function, specify them after you call get_defined_vars, e.g.:

function foo($arg1, $arg2)
{
    $passed = get_defined_vars();

    static $staticVariable = 0;
    global $staticVariable;
    ...
}

Take care that this is not the same as func_get_argsDocs which will also contain passed but not defined function arguments. Also default arguments aren't part of func_get_args but naturally get_defined_vars will have them with their default value.

like image 119
hakre Avatar answered Nov 03 '22 15:11

hakre


You should require that the arguments themselves not be arguments, but rather, an associative array:

public function yourMethod(array $args = array()) {
    if (array_key_exists('foo', $args)) {
        // foo
    }

    // ...
}

$obj->yourMethod(array(
    'foo' => 'foo value',
    'bar' => 'bar value'
));
like image 41
FtDRbwLXw6 Avatar answered Nov 03 '22 16:11

FtDRbwLXw6