2

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?

1
  • You'd need to use ReflectionMethod::getParameters() for that. Not a real issue to write something for it, but do take into account this creates some overhead. Commented Nov 18, 2014 at 21:56

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I was hoping there would be a method for this but I figured you may have to do something like this. Good answer!
ReflectionMethod doesn't have a method getArguments. The correct one is $reflectionmethod->getParameters() php.net/manual/ro/reflectionfunctionabstract.getparameters.php
@DaniDudas: thanks for pointing that out (could have sworn I tested it back then, but the manual says otherwise indeed). BTW: you can always suggest an edit, which works a bit quicker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.