简体   繁体   中英

Pass-by-Reference Error

I have a hook system setup... which is working on localhost... I put it live and get an error saying "Warning: Call-time pass-by-reference has been deprecated".

Now, apparently the work around is to remove all "&" from your function calls, ie foo(&$me) to foo($me) and then in foo's function definition do "function foo(&$me)".

However, I can not do this... because my hooks accept an array as arguments, I need a work around for this. Like I can use "run_hooks ( 'hook-name', $me );" or "run_hooks ( 'hook-name', array ( $me, $another_var, etc... ) )";

So this means I can not use "function run_hooks ( $hook_name, &$arguments )" because I'll get an error in php saying it can not pass "array()" as reference...

Any ideas an a work around?

Thanks.

I guess you want to use a reference in order to prevent unnecessary copies of data. But that's not what you should use them for (in php5). Simply pass the array.

function foo($x /* not a reference */) {
  echo $x['bar'], "\n";
} 
$p = array('bar'=>12345);
foo($p);
// or
foo( array('bar'=>12345) );

This invokes no deep copy of the array that is passed as parameter - as long as you don't change the array. This mechanism is called copy-on-write and the php implementation is explained in http://www.research.ibm.com/trl/people/mich/pub/200901_popl2009phpsem.pdf

Pass an array of references around - this array itself doesn't need to be a reference:

 function foo($args) {
    modify $args[0]...
    modify $args[1]...
 }

 $someVar = ...
 $anotherVar = ...

 foo(array(&$someVar, &$anotherVar));

I think I found a viable workaround, no errors, and it does work without modifying anything in my classes... could help anyone else... ArrayObject solved it, seince objects are already 'referenced'.

function test ( $var, $foo )
{
    $var    = 3;
    $foo    = 3;
}

$var    = 1;
$foo    = 1;
call_user_func_array ( 'test', new ArrayObject ( array ( &$var, &$foo ) ) );

print $foo;
print $var;

// Output is 3 3 like expected :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM