Re: function by reference

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



The ampersand before the function name indicates that the function returns a
reference instead of a copy of the variable, for example:

<?php
  function &max(&$var1, &$var2) {
    if ($var1 > $var2) return $var1;
    else return $var2;
  }

  $global1 = 10;
  $global2 = 9;
  $maxglobal =& max($global1, $global2);
  $maxglobal++;
  echo $global1;
  //this will print 11 since $maxglobal is a reference to $global1
?>

2006/4/11, tedd <tedd@xxxxxxxxxxxx>:
>
>
> Additionally, what I don't get is this:
>
> <?php
>         $a = 10;
>         echo("$a <br/>");
>         ref1(&$a);
>         echo("$a <br/>");
>
>         $a = 10;
>         echo("$a <br/>");
>         ref2($a);
>         echo("$a <br/>");
>
>         $a = 10;
>         echo("$a <br/>");
>         ref3($a);
>         echo("$a <br/>");
>
> ?>
>
>
> <?php
>         function ref1($a)
>                 {
>                 $a--;
>                 }
>
> ?>
>
> <?php
>         function ref2(&$a)
>                 {
>                 $a--;
>                 }
>
> ?>
>
> <?php
>         function &ref3($a)
>                 {
>                 $a--;
>                 }
>
> ?>
>
> The first two functions work as I would expect. The last one is shown
> in the documentation, but doesn't work as I expected. There doesn't
> appear to be any difference between ref1 and ref3 -- so what's with
> the "ampersand" in &ref3? What is an ampersand supposed to mean/do
> when it precedes a function?
>
> Thanks.
>
> tedd
> --
>
> --------------------------------------------------------------------------------
> http://sperling.com
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux