views:

188

answers:

3

Hello,

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

+2  A: 

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
but what if i don't know beforehand whether they are passed by reference or passed by value?
Sarfraz
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
+3  A: 

You cannot pass arguments by reference to functions called with callbacks. The reason is that call_user_func_array()s parameters are not references. If you really need to do it with a callback, you will need to wrap the parameters into an object (objects are always passed by reference):

function test($params) {
    echo $params->param1;
    echo $params->param2;
}
$params = (object) array('param1' => $param1, 'param2' => $param2);
call_user_func_array('test', array($params));
soulmerge
thanks for such great explanation :)
Sarfraz
See the manual section "Objects and references" which explains why it's "not completely true" that "objects are always passed by reference", and demonstrates why the difference matters.
GZipp
For future reference: this is the link to the article GZipp was mentioning: http://www.php.net/manual/en/language.oop5.references.php
soulmerge
A: 

I'm getting a similar issue with drupal project OpenScholar on Fedora with php 5.3.x.

warning: call_user_func_array() expects parameter 2 to be array, string given in /var/www/html/sites/all/modules/contrib/views/views.module on line 451.

I'm trying the following test. Taking line 451 from

   if (function_exists($callback) && call_user_func_array($callback, $argments)) {
     return TRUE;
   }

to (notice: array($argments))

   if (function_exists($callback) && call_user_func_array($callback, array($argments))) {
 return TRUE;

}

This seem to work for me! :)

Richard