note 76816 deleted from function.call-user-func-array by danbrown

From: Date: Sat, 19 Jul 2008 20:55:52 +0000
Subject: note 76816 deleted from function.call-user-func-array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-141733@lists.php.net to get a copy of this message
Note Submitter: php at paulbutler dot org ---- There is weird behavior on this function in terms of passing variables by reference. It seems that despite what the manual says, if a reference to the variable exists it will be passed by reference. For instance, take the following code: <?php function setargs(&$a1, &$a2, &$a3){ $a1 = "one"; $a2 = "two"; $a3 = "three"; } $args = array('1','2','3'); call_user_func_array('setargs', $args); echo implode(' ', $args); ?> The above code will display "1 2 3", indicating that the variables were passed by value. However, take the following code: <?php function setargs(&$a1, &$a2, &$a3){ $a1 = "one"; $a2 = "two"; $a3 = "three"; } $args = array('1','2','3'); $hack = array(); for($i = 0; $i < count($args); $i++){ $hack[] =& $args[$i]; } call_user_func_array('setargs', $args); echo implode(' ', $args); ?> Which displays "one two three", instead of the expected "1 2 3". This appears to be a bug in PHP, but it is a useful one because it makes it possible to pass variables by reference to a user function call. Of course it is dangerous to rely on a hack, especially one that only works because of a bug, but if you know what you are doing this could help you get around this limitation of call_user_func_array.

« previous php.notes (#141733) next »