Re: function by reference

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

 



Well, it was a bad example to begin with, first of all max() is already defined in php, I should at least checked that before posting. Second, I forgot PHP (the Zend engine) has an interesting way of handling variables, when you copy assign a var or pass it as an argument of a function, a real copy is not made but a reference. When you modify the reference, an actual copy is made before the modification. What's happening with the function you posted is that the variables are not passed by copy but by reference, that's why it works. Anyway, this is due to conditions on the way PHP (the Zend engine) handles its internal, you shouldn't rely on this in your code.

http://www.zend.com/zend/art/ref-count.php

tedd wrote:

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
?>


It's going to hurt thinking about that.  :-)

But that produces the same results as:

<?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
?>

Note the absence ampersands in the function, but an ampersand remains in the assignment:

Thanks.

tedd

--
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