6

The below function generates error when a function contains referenced arguments eg:

function test(&$arg, &$arg2)
{
  // some code
}

Now I can not use call_user_func_array for above function, it will generate an error.

How to solve this problem?

I do need to use call_user_func_array.

Also assume that i don't know beforehand whether they are passed by reference or passed by value.

Thanks

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 4
    It would be worth while for you to unaccept the current answer as it is quite literally wrong (not to mention has bad advice by abusing objects which changes the semantics of the problem completely): http://codepad.viper-7.com/j3GOps – ircmaxell Dec 01 '11 at 17:22

2 Answers2

22

When storing your parameters in the array, make sure you are storing a reference to those parameters, it should work fine.

Ie:

call_user_func_array("test", array(&param1, &param2));
Myles
  • 20,860
  • 4
  • 28
  • 37
  • 2
    but what if i don't know beforehand whether they are passed by reference or passed by value? – Sarfraz Dec 15 '09 at 07:54
  • 1
    Then figure out a way to determine that, or make them all pass by reference would be my suggestion. Not much else you can do I'm afraid. – Myles Dec 15 '09 at 07:58
  • Myles: what if I don't know amount of arguments in the array? – ymakux Aug 03 '15 at 15:43
  • @ymakux ultimately you need an array of references. You'll be passing *something* so just create an array from whatever that something is. – Myles Aug 03 '15 at 15:45
  • yes, right, seems call_user_func_array becomes useless in my case, i have to write spaghetti code instead of this switch(count($args)) { case 0: $class->{$method}(); break; case 1: } – ymakux Aug 03 '15 at 16:36
7

A great workaround was posted on http://www.php.net/manual/de/function.call-user-func-array.php#91503

function executeHook($name, $type='hooks'){ 
    $args = func_get_args(); 
    array_shift($args); 
    array_shift($args); 
    //Rather stupid Hack for the call_user_func_array(); 
    $Args = array(); 
    foreach($args as $k => &$arg){ 
        $Args[$k] = &$arg; 
    } 
    //End Hack 
    $hooks = &$this->$type; 
    if(!isset($hooks[$name])) return false; 
    $hook = $hooks[$name]; 
    call_user_func_array($hook, $Args); 
} 

The actual hack is surrounded by comments.

Björn Tantau
  • 1,564
  • 14
  • 13