note 53268 deleted from language.references.pass by danbrown
| From: | danbrown@php.net | Date: | Thu, 28 Jan 2010 13:20:18 +0000 |
| Subject: | note 53268 deleted from language.references.pass by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165423@lists.php.net to get a copy of this message | ||
Note Submitter: Andy Morris
----
"jbr at diasparsoftware dot com" spotted something strange when calling call_user_func()
where the user function was declared as expecting a reference and seemed to contradict the manual.
Actually, the manual says that parameters to call_user_func() aren't passed as references,
which I take to mean that if you declare your user function as expecting a parameter by reference,
this won't work. In jbr's test code, this doesn't work - so this part isn't a
surprise.
However, the manual goes on to say that the way out of the problem is to use call_user_func_array()
and pass the parameter by reference in an array instead. For example, see this code (from the
call_user_func manual page)...
<?php
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func('increment', $a);
echo $a; // 0
call_user_func_array('increment', array(&$a)); // You can use this instead
echo $a; // 1
// I've added this call to illustrate something strange...
call_user_func('increment', &$a); // but look - just adding & works too!
echo $a; // 2
?>
The strange thing that "jbr at diasparsoftware dot com" discovered is that you don't
actually have to use call_user_func_array() at all, so long as you explicitly specify the variable
to be passed by reference when actually calling your function via call_user_func().
Is this just a lucky coincidence? I'm still hunting in the manual to see whether this really is
just lucky, or a simpler correct way to do it.