PHP 5.3: pass by reference problems

Submitted by Jochus on Wed, 11/08/2010 - 00:57 | Posted in: Drupal

Interesting problem in the new PHP 5.3 (I'm currently using 5.3.2-1ubuntu4.2).

Imagine you have following code:
-> Function test() takes 2 arguments. The 2 arguments are referenced arguments (notice the '&'):

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

... and you want to call it using the call_user_func_array() function.
In PHP 5.2 (or lower), you could simply do this by:

call_user_func_array('test', $arg1, $arg2);

... but since PHP 5.3, this will not work any longer :-). You cannot pass arguments by reference to functions called with callbacks. The reason is that call_user_func_array() 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){
  // some code
  echo $params->arg1;
  echo $params->arg2;
}
...
$params = (object) array('arg1' => $arg1, 'arg2' => $arg2);
call_user_func_array('test', $params);

Add new comment

The content of this field is kept private and will not be shown publicly.

Full HTML

  • Lines and paragraphs break automatically.
  • You can caption images (data-caption="Text"), but also videos, blockquotes, and so on.
  • Web page addresses and email addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <cpp>, <css>, <html5>, <java>, <javascript>, <php>, <sql>, <xml>. The supported tag styles are: <foo>, [foo].
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.