[nycphp-talk] passing optional arguments by reference
Dan Cech
dcech at phpwerx.net
Fri Jan 16 11:47:26 EST 2004
Daniel Convissor wrote:
> Hi Folks:
>
> I'm want the parameters for a function to be passed by reference.
> Normally, that's accomplished by placing a & in front of the variable.
> Trick is, the argument in question needs to be optional. Placing a & in
> front of an optional parameter creates a parse error.
>
> CODE:
> function &execute($stmt, &$data = array()) {
> }
>
> ERROR:
> Parse error: parse error, unexpected '=', expecting ')'
>
> Removing the "= array()" makes it parse fine.
>
> So, is there a way to do this, please?
AFAIK, no.
There is a workaround though. If you create an array containing a
reference, then pass that array normally, your function will work on a
copy of the array, which contains a copy of the reference, which will
still reference the same object.
If that didn't make any sense:
$myobj =& new stdClass ();
print_r ($myobj);
$myarr = array ();
$myarr['myobj'] =& $myobj;
function myfunc ($input = array ())
{
if ( isset ($input['myobj']) )
{
$input['myobj']->test = TRUE;
}
}
myfunc ($myarr);
print_r ($myobj);
Hope this helps,
Dan
> Thanks,
>
> --Dan
>
More information about the talk
mailing list