Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing named parameters to a php function through call_user_func_array

Tags:

function

php

When trying to call a function in a child class with an arbitrary set of parameters, I'm having the following problem:

class Base{

    function callDerived($method,$params){
        call_user_func_array(array($this,$method),$params);
    }
}

class Derived extends Base{
    function test($foo,$bar){
        print "foo=$foo, bar=$bar\n";
    }
}

$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));

Outputs:

foo=2, bar=1

Which... is not exactly what I wanted - is there a way to achieve this beyond re-composing the array with the index order of func_get_args? And yes, of course, I could simply pass the whole array and deal with it in the function... but that's not what I want to do.

Thanks

like image 345
Wagemage Avatar asked Jul 07 '11 12:07

Wagemage


1 Answers

No. PHP does not support named parameters. Only the order of parameters is taken into account. You could probably take the code itself apart using the ReflectionClass to inspect the function parameter names, but in the end you'd need to use this to reorder the array anyway.

like image 98
deceze Avatar answered Sep 19 '22 12:09

deceze