Uberswe
Uberswe

Reputation: 1058

call_user_func_array() args with strings as keys to match function args names

At the moment I have something like this

function callFunction($method, $args) {
    if(method_exists($this, $method)) {
            call_user_func_array(array($this, $method), $args);
    }
}

function myfunction ($hello, $world, $blah) {
}

where $args is an array like [0] => 'string1', [1] => 'string2', [2] => 'string3' which gets passed to the function in that order. However would there be a way to have the keys to the args match the functions argument names. like ['hello'] => 'string1', ['world'] => 'string2', ['blah'] => 'string3' where they could be in any order and be matched to the correct argument name by key?

Upvotes: 2

Views: 835

Answers (1)

Wrikken
Wrikken

Reputation: 70490

Quite some overhead, but possible:

function callFunction($method, $args) {
    if(method_exists($this, $method)) {
         $arguments = array();
         $reflectionmethod = new ReflectionMethod($this,$method);
         foreach($reflectionmethod->getParameters() as $arg){
             if(isset($args[$arg->name])){
                 $arguments[$arg->name] = $args[$arg->name];
             } else if($arg->isDefaultValueAvailable()){
                 $arguments[$arg->name] = $arg->getDefaultValue();
             } else {
                 $arguments[$arg->name] = null;
             }
         }
         call_user_func_array(array($this, $method), $arguments);
    }
}

function myfunction ($hello, $world, $blah) {
}

Something that is passed by reference would be iffy though. You'd probably need some more code to make that work. Long story short: PHP ain't Python :)

Upvotes: 3

Related Questions