note 76816 added to function.call-user-func-array
| From: | php at paulbutler dot org | Date: | Tue, 31 Jul 2007 22:13:08 +0000 |
| Subject: | note 76816 added to function.call-user-func-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129087@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 216.235.15.211
Probable Submitter: 24.222.124.6
----
Manual Page -- http://www.php.net/manual/en/function.call-user-func-array.php
Edit -- https://master.php.net/note/edit/76816
Del: integrated -- https://master.php.net/note/delete/76816/integrated
Del: useless -- https://master.php.net/note/delete/76816/useless
Del: bad code -- https://master.php.net/note/delete/76816/bad+code
Del: spam -- https://master.php.net/note/delete/76816/spam
Del: non-english -- https://master.php.net/note/delete/76816/non-english
Del: in docs -- https://master.php.net/note/delete/76816/in+docs
Del: other reasons-- https://master.php.net/note/delete/76816
Reject -- https://master.php.net/note/reject/76816
Search -- https://master.php.net/manage/user-notes.php