Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: call_user_func_array: pass by reference issue

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

like image 563
Sarfraz Avatar asked Dec 15 '09 07:12

Sarfraz


2 Answers

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));
like image 66
Myles Avatar answered Sep 28 '22 10:09

Myles


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.

like image 43
Björn Tantau Avatar answered Sep 28 '22 09:09

Björn Tantau