phparraysassociative-arraynamed-parametersfunction-parameter

Is it possible to pass an associative array to a function and have those elements treated as individual parameters?


In short, what I want is a kind of export() function (but not export()), it creates new variables in a symbols table and returns the number of created vars.

I'm trying to figure out if it is possible to declare a function

function foo($bar, $baz)
{
    var_dump(func_get_args());
}

And after that pass an array so that each value of array would represent parameters.

Just wondering if it is possible (seems that is not).

I need this for dynamic loading, so number of arguments, size of array may vary - please don't offer to pass it as

foo($arr['bar']);

and so on.

Again, ideal thing solution will look like

foo(array('foo'=>'1', 'bar'=>'2', ..., 'zzz'=>64));

for declaration

function foo($foo, $bar, ..., $zzz) {}

As far as I rememeber in some dynamic languages lists may behave like that (or maybe I'm wrong).

(I want to create dynamically parameterized methods in a class and enjoy a built-in mechanism of controlling functions' number of arguments, default value, and so on. Such a mechanism would allow me to get rid of array params and func_get_args() and func_get_num() calls in the method body).


Solution

  • You're looking for call_user_func_array

    example:

    function foo($bar, $baz)
    {
        return call_user_func_array('beepboop',func_get_args());
    }
    
    function beepboop($bar, $baz){
        print($bar.' '.$baz);
    }
    
    foo('this','works');
    //outputs: this works